using System;
using System.IO;
using Newtonsoft.Json;
using ProtoBuf;
// https://github.com/protobuf-net/protobuf-net
namespace TopNugetPackages
{
[ProtoContract]
internal class Person
{
[ProtoMember(1)]
public int Id { get; set; }
[ProtoMember(2)]
public string Name { get; set; }
[ProtoMember(3)]
public Address Address { get; set; }
}
[ProtoContract]
internal class Address
{
[ProtoMember(1)]
public string Line1 { get; set; }
[ProtoMember(2)]
public string Line2 { get; set; }
}
// Sample usage of protocol buffers (from Google)
// This is the simplified version using protobuf-net
// Serializes data into a binary file, then deserialize into an object.
// Usefull for cross platform, cross language communication of objects.
public class MainProtoBufDriver
{
public void DoIt()
{
// Arrange
var person = new Person
{
Id = 12345,
Name = "Fred",
Address = new Address
{
Line1 = "Flat 1",
Line2 = "The Meadows"
}
};
File.Delete("person.bin");
// Serialize binary data into file
using (var file = File.Create("person.bin"))
{
Serializer.Serialize(file, person);
}
// Deserialize binary data from file into object
Person newPerson;
using (var file = File.OpenRead("person.bin"))
{
newPerson = Serializer.Deserialize<Person>(file);
}
// now lets check it
var json = JsonConvert.SerializeObject(newPerson, Formatting.Indented);
Console.WriteLine(json);
}
}
}