假设我有以下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
Point
circle
和person
说明此方法的完整程序如下所示。
必须先反序列化,序列化然后再反序列化,这似乎有点a回。我的问题是,有没有更好的方法?
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));
}
}
}
}
}