反序列化不同类型的JSON数组

29 浏览
0 Comments

反序列化不同类型的JSON数组

假设我有以下的JSON数组:

[

{ "type": "point", "x": 10, "y": 20 },

{ "type": "circle", "x": 50, "y": 50, "radius": 200 },

{ "type": "person", "first_name": "Linus", "last_name": "Torvalds" }

]

我想将这个数组的元素反序列化为以下类的实例,根据type字段的值:

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;
}

一种方法是按照以下步骤进行:

  • 使用JArray.Parse反序列化JSON。数组中的元素现在可以被视为dynamic对象。
  • 对于数组中的每个dynamic元素

    • 如果type字段等于point

      • 将此元素序列化回JSON
      • 将JSON反序列化为Point
    • circleperson类似

下面是一个完整的程序示例,演示了这种方法。

需要进行反序列化、序列化,然后再次反序列化似乎有点绕弯。我的问题是,是否有更好的方法?

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(JsonConvert.SerializeObject(elt));
                }
                else if (elt.type == "circle")
                {
                    var circle = JsonConvert.DeserializeObject(JsonConvert.SerializeObject(elt));
                }
                else if (elt.type == "person")
                {
                    var person = JsonConvert.DeserializeObject(JsonConvert.SerializeObject(elt));
                }
            }
        }
    }
}

0