C# 反序列化不同类型的JSON数组
假设我有以下JSON数组:C# 反序列化不同类型的JSON数组,c#,json.net,C#,Json.net,假设我有以下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 { p
[
{ "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;
}
一种方法是执行以下操作:
- 使用
反序列化JSON。现在可以将数组中的元素视为JArray.Parse
对象动态
- 对于数组中的每个
动态
元素
- 如果
字段等于类型
点
- 将此元素序列化回JSON
- 将JSON反序列化为
点
- 类似于
和圆圈
人
- 如果
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));
}
}
}
}
}
使用Newtonsoft.Json;
使用Newtonsoft.Json.Linq;
命名空间JsonArrayDifferentTypes
{
公共课点
{
公共int x;
公共智力;
}
公共阶级圈子
{
公共int x;
公共智力;
公共整数半径;
}
公共阶层人士
{
公共字符串名称;
公共字符串姓氏;
}
班级计划
{
静态void Main(字符串[]参数)
{
var json=System.IO.File.ReadAllText(@“c:\temp\json数组不同类型.json”);
var obj=JArray.Parse(json);
foreach(obj中的动态elt)
{
如果(elt.type==“点”)
{
var point=JsonConvert.DeserializeObject(JsonConvert.SerializeObject(elt));
}
else if(elt.type==“圆圈”)
{
var circle=JsonConvert.DeserializeObject(JsonConvert.SerializeObject(elt));
}
else if(elt.type==“个人”)
{
var person=JsonConvert.DeserializeObject(JsonConvert.SerializeObject(elt));
}
}
}
}
}
看看我链接的问题。有一个机制,但它不是很好看。添加了一些重复。看看我链接到的问题。有一个机制,但它不是所有伟大的期待。增加了一些重复。