protobuf-net是否支持嵌套类?
属性类型名称和顺序是否正确?
作为下面的代码,使用替代属性XmlType / XmlElement而不是ProtoContract / ProtoInclude
using System.Xml.Serialization;
[XmlType("Person")]
public class Person
{
[XmlElement(ElementName = "Display Name",Order = 1)]
public string Name { get; set; }
[XmlElement(ElementName = "Age", Order = 2)]
public byte Age { get; set; }
[XmlType("Person.Address")]
public class Address
{
[XmlElement(ElementName = "Street",Order = 1)]
// before I had Order=3 to be unique, but as Mark says
// the "Order only needs to be unique inside a single type"
public string Street { get; set; }
[XmlElement(ElementName = "ZIP",Order =2)]
public string Zip { get; set; }
}
}
更新,在我的回答中,我写了最后一节课,用protobuf实现ServiceStack服务。
答案 0 :(得分:2)
在Marc Gravell的帮助下,我理解了嵌套类在protobuf中是如何工作的。
我使用ServiceStack(版本3.9.71)服务测试它,它工作正常。
这是模型。
using System.Xml.Serialization;
[XmlType("Person")]
public class Person
{
[XmlElement(ElementName = "Display Name", Order = 1)]
public string Name { get; set; }
[XmlElement(ElementName = "Age", Order = 2)]
public byte Age { get; set; }
[XmlElement(ElementName = "Contact Address", Order =3)] // the address instance
public Address ContactAddress { get; set; }
[XmlElement(ElementName = "Person Id", Order = 4)]
public int Id { get; set; }
[XmlType("Person.Address")]
public class Address
{
[XmlElement(ElementName = "Street", Order = 1)]
// before I had Order=5 to be unique, but as Mark says
// the "Order only needs to be unique inside a single type"
public string Street { get; set; }
[XmlElement(ElementName = "ZIP", Order = 2)]
public string Zip { get; set; }
}
}
ServiceStack请求
public class PersonRequest
{
public string Zip { get; set; }
public byte Age { get; set; }
public int Id { get; set; }
}
public class AddressRequest
{
public string Zip { get; set; }
}
AppHack路由AppHost.Configure。 (自托管服务)
Routes
.Add<PersonRequest>("/Person/{Id}", "GET, OPTIONS")
.Add<PersonRequest>("/Persons/{Zip}", "GET, OPTIONS")
.Add<AddressRequest>("/Addresses/{Zip}", "GET, OPTIONS");
服务
首先,我们使用Zip过滤器询问带有联系地址的人员列表
第二种情况,使用Zip过滤器的地址列表,与人无关
public List<Person> Get(PersonRequest request)
{
List<Person> persons=new List<Person>();
persons.Add(new Person()
{ Name = "stefan", ContactAddress = new Person.Address(){Street="North Pole"}});
return persons;
}
public List<Person.Address> Get(AddressRequest request)
{ // it returns only addresses filtered by Zip
List<Person.Address> addresses=new List<Person.Address>();
addresses.Add( new Person.Address() { Street = "North Pole" } );
return addresses;
}
ServiceStack客户端代码,使用ProtoBufServiceClient
using ServiceStack.Plugins.ProtoBuf;
...
var client = new ProtoBufServiceClient(serverUri);
List<Person> persons = client.Get<List<Person>>(serverUri + @"/Persons/600617");
List<Person.Address> addresses =
client.Get<List<Person.Address>>(serverUri + @"/Addresses/600617");
非常感谢,Marc。