In order to facilitate work with a specific component, it is necessary to derive a new class, PagedResult
Json.Net treats classes implementing IEnumerable as arrays by default. While decorating the class with a [JsonObject] attribute can override this behavior, it only serializes object properties, leaving the list un-serialized. This is because the list is not accessible through a public property but via the GetEnumerator() method.
To include both, you can either make a public property in your derived class accessible to the list, as suggested by @Konrad, or create a custom JsonConverter to serialize the entirety of the object. Below is an example:
Assuming PagedResult
class PagedResult<T> : List<T> { public int PageSize { get; set; } public int PageIndex { get; set; } public int TotalItems { get; set; } public int TotalPages { get; set; } }
Here's how to create a custom converter:
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("PageSize", result.PageSize); jo.Add("PageIndex", result.PageIndex); jo.Add("TotalItems", result.TotalItems); jo.Add("TotalPages", result.TotalPages); 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>(); result.PageSize = (int)jo["PageSize"]; result.PageIndex = (int)jo["PageIndex"]; result.TotalItems = (int)jo["TotalItems"]; result.TotalPages = (int)jo["TotalPages"]; result.AddRange(jo["Items"].ToObject<T[]>(serializer)); return result; } }
(Note that [JsonObject] and [JsonProperty] are not necessary with this approach, as the knowledge of what to serialize is encoded in the converter class.)
Below is a demonstration using the converter:
class Program { static void Main(string[] args) { PagedResult<string> result = new PagedResult<string> { "foo", "bar", "baz" }; result.PageIndex = 0; result.PageSize = 10; result.TotalItems = 3; result.TotalPages = 1; JsonSerializerSettings settings = new JsonSerializerSettings(); settings.Converters.Add(new PagedResultConverter<string>()); settings.Formatting = Formatting.Indented; string json = JsonConvert.SerializeObject(result, settings); Console.WriteLine(json); } }
Output:
{ "PageSize": 10, "PageIndex": 0, "TotalItems": 3, "TotalPages": 1, "Items": [ "foo", "bar", "baz" ] }
The above is the detailed content of How to Serialize a List-Derived Class with Additional Members Using Json.NET?. For more information, please follow other related articles on the PHP Chinese website!