【发布时间】:2012-02-09 03:48:12
【问题描述】:
我想序列化(以 JSON 格式)一个对象列表,其中每个对象都具有另一种对象的属性。这是我到目前为止所得到的:
[DataContract]
public class Person{
[DataMember]
public string Name { get; set; }
[DataMember]
public Address FullAddress { get; set; }
}
[DataContract]
public class Address {
private readonly byte[] _foo;
private ulong _value;
public byte[] Foo { get { return (byte[]) _foo.Clone(); }}
public ulong Value { get { return _value; } set { return _value; }}
public Address(byte [] bytes){
_foo = new byte[bytes.Length];
Array.Copy(bytes, _foo, bytes.Length);
foreach(byte b in _foo){
_value |= b; // I do some bit manipulation here and modify the _value
}
}
public MacAddress() // added this otherwise I get an exception
{
}
}
这就是我序列化和反序列化的方式:
public class MyJson{
public MyJson(){
var list = new List<Person>{ /* added a bunch of person here */ };
var serializer = new JavaScriptSerializer();
string json = serializer.Serialize(list);
// serialization works fine
var desList = serializer.Deserialize<IList<Person>>(json);
// the deserialization doesn't properly deserialize Address property.
}
}
如上所述,序列化工作正常,但反序列化不能正确反序列化地址。我得到了 Value 属性的数字(如预期的那样),但没有得到 Foo 的数字(我知道它缺少一个设置器,但是如果由于某种原因我不能放置一个设置器怎么办?)。
我在这里错过了什么?
【问题讨论】:
标签: c# .net json serialization deserialization