JSON.NET与自定义集合(含集合属性) [英] JSON.NET with custom collection (with collection properties)
问题描述
我有一个自定义集合(实现IList),其中有一些自定义属性如下
I have a custom collection (implements IList) which has some custom properties as following
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其识别为一个数组值和序列化它下面的数组 JSON的语法(不包括物业),
例如
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与自定义集合(含集合属性)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!