Home > Backend Development > C++ > How to Serialize a List-Derived Class with Additional Members Using Json.NET?

How to Serialize a List-Derived Class with Additional Members Using Json.NET?

DDD
Release: 2025-01-07 13:07:41
Original
395 people have browsed it

How to Serialize a List-Derived Class with Additional Members Using Json.NET?

How to Serialize Members of a Class Deriving from List Using Json.net

In order to facilitate work with a specific component, it is necessary to derive a new class, PagedResult, from List and include additional members. However, upon running the JSON deserializer, only the list is serialized. Using the [JsonObject] and [JsonProperty] attributes on the derived class only serializes the derived class members, excluding the list. This article explores how to serialize both the list and its derived class members.

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 exists as:

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; }
}
Copy after login

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;
    }
}
Copy after login

(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);
    }
}
Copy after login

Output:

{
  "PageSize": 10,
  "PageIndex": 0,
  "TotalItems": 3,
  "TotalPages": 1,
  "Items": [
    "foo",
    "bar",
    "baz"
  ]
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template