
Json.Net: Serialize Members of a Class Derived from List
Json.Net by default treats classes that implement IEnumerable as arrays. To override this behavior, mark the derived class with [JsonObject] and [JsonProperty] attributes. However, this only serializes the members of the derived class, not the list.
To serialize both the derived class members and the list, provide a public property on the derived class to expose the list:
class PagedResult<T> : List<T>
{
public IEnumerable<T> Items { get { return this; } }
}Alternatively, create a custom JsonConverter to serialize the whole thing:
class PagedResultConverter<T> : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return (objectType == typeof(PagedResult<T>));
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
PagedResult<T> result = (PagedResult<T>)value;
JObject jo = new JObject();
jo.Add("Properties", JObject.FromObject(result, serializer));
jo.Add("Items", JArray.FromObject(result.ToArray(), serializer));
jo.WriteTo(writer);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
JObject jo = JObject.Load(reader);
PagedResult<T> result = new PagedResult<T>();
jo["Properties"].ToObject<PagedResult<T>>(serializer);
result.AddRange(jo["Items"].ToObject<T[]>(serializer));
return result;
}
}Register the converter in the JsonSerializerSettings:
JsonSerializerSettings settings = new JsonSerializerSettings(); settings.Converters.Add(new PagedResultConverter<T>());
The above is the detailed content of How to Serialize a Class Derived from List in Json.Net while Preserving Both Custom Properties and List Items?. For more information, please follow other related articles on the PHP Chinese website!