问题描述
我有一个自定义集合(实现IList),其中有一些自定义属性,如下所示:
I have a custom collection (implements IList) which has some custom properties as shown below:
class FooCollection : IList<Foo> {
private List<Foo> _foos = new List<Foo>();
public string Bar { get; set; }
//Implement IList, ICollection and IEnumerable members...
}
当我序列化,我用下面的code:
When I serialize, I use the following code:
JsonSerializerSettings jss = new JsonSerializerSettings() {
TypeNameHandling = TypeNameHandling.Auto
};
string serializedCollection = JsonConvert.SerializeObject( value , jss );
据序列化和反序列化正确所有收集的物品;然而,在任何额外的属性的 FooCollection
类都没有考虑到
反正是有,包括他们的序列化?
Is there anyway to include them in the serialization?
推荐答案
这个问题是这样的:当一个对象实现的IEnumerable
,JSON.net将其标识为一个数组值的和序列化之后的阵列它的(即不包括属性),
例如
The problem is the following: when an object implements IEnumerable
, JSON.net identifies it as an array of values and serializes it following the array Json syntax (that does not include properties),e.g. :
[ {"FooProperty" : 123}, {"FooProperty" : 456}, {"FooProperty" : 789}]
如果你想序列化保持属性,需要通过定义一个定制 JsonConverter
来处理用手该对象的序列化:
If you want to serialize it keeping the properties, you need to handle the serialization of that object by hand by defining a custom JsonConverter
:
// intermediate class that can be serialized by JSON.net
// and contains the same data as FooCollection
class FooCollectionSurrogate
{
// the collection of foo elements
public List<Foo> Collection { get; set; }
// the properties of FooCollection to serialize
public string Bar { get; set; }
}
public class FooCollectionConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return objectType == typeof(FooCollection);
}
public override object ReadJson(
JsonReader reader, Type objectType,
object existingValue, JsonSerializer serializer)
{
// N.B. null handling is missing
var surrogate = serializer.Deserialize<FooCollectionSurrogate>(reader);
var fooElements = surrogate.Collection;
var fooColl = new FooCollection { Bar = surrogate.Bar };
foreach (var el in fooElements)
fooColl.Add(el);
return fooColl;
}
public override void WriteJson(JsonWriter writer, object value,
JsonSerializer serializer)
{
// N.B. null handling is missing
var fooColl = (FooCollection)value;
// create the surrogate and serialize it instead
// of the collection itself
var surrogate = new FooCollectionSurrogate()
{
Collection = fooColl.ToList(),
Bar = fooColl.Bar
};
serializer.Serialize(writer, surrogate);
}
}
然后按如下方式使用它:
Then use it as follows:
var ss = JsonConvert.SerializeObject(collection, new FooCollectionConverter());
var obj = JsonConvert.DeserializeObject<FooCollection>(ss, new FooCollectionConverter());
这篇关于如何序列化/反序列化使用附加属性自定义集合Json.Net的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!