1

Let's say I have the following JSON array:

[
    { "type": "point", "x": 10, "y": 20 },
    { "type": "circle", "x": 50, "y": 50, "radius": 200 },
    { "type": "person", "first_name": "Linus", "last_name": "Torvalds" }
]

I'd like to deserialize the elements of this array into instances of the following classes, according to the type field:

public class Point
{
    public int x;
    public int y;
}

public class Circle
{
    public int x;
    public int y;
    public int radius;
}

public class Person
{
    public string first_name;
    public string last_name;
}

One approach is to do the following:

  • Deserialize JSON using JArray.Parse. The elements in the array can now be treated as dynamic objects.
  • For each dynamic element in the array
    • If the type field is equal to point
      • Serialize this element back into JSON
      • Deserialize the JSON into a Point
    • Similar for circle and person

A full program illustrating this approach is shown below.

Having to deserialize, serialize, and then deserialize again seems like a bit of a roundabout way. My question is, is there a better approach?

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace JsonArrayDifferentTypes
{
    public class Point
    {
        public int x;
        public int y;
    }

    public class Circle
    {
        public int x;
        public int y;
        public int radius;
    }

    public class Person
    {
        public string first_name;
        public string last_name;
    }

    class Program
    {
        static void Main(string[] args)
        {
            var json = System.IO.File.ReadAllText(@"c:\temp\json-array-different-types.json");

            var obj = JArray.Parse(json);

            foreach (dynamic elt in obj)
            {
                if (elt.type == "point")
                {
                    var point = JsonConvert.DeserializeObject<Point>(JsonConvert.SerializeObject(elt));
                }
                else if (elt.type == "circle")
                {
                    var circle = JsonConvert.DeserializeObject<Circle>(JsonConvert.SerializeObject(elt));
                }
                else if (elt.type == "person")
                {
                    var person = JsonConvert.DeserializeObject<Person>(JsonConvert.SerializeObject(elt));
                }
            }

        }
    }
}
dharmatech
  • 8,979
  • 8
  • 42
  • 88

0 Answers0