【发布时间】:2019-12-04 19:46:42
【问题描述】:
我正在检索一个包含多个对象类型的数组的 json 对象。
假设我检索到如下所示的 JSON 有效负载:
{
"Lines": [
{
"PropertyA": "A",
"PropertyB": "B"
},
{
"Property01": 1,
"Property02": 2
}]
}
我想将其反序列化为单个对象列表。
例子:
public List<Line> Lines;
所以我可以将对象与我期望的对象进行比较。
到目前为止我所拥有的:
public class Class1
{
public string PropertyA = "A";
public string PropertyB = "B";
}
public class Class2
{
public int Property01 = 01;
public int Property02 = 02;
}
public class MainClass
{
public List<dynamic> Lines;
}
class Program
{
static void Main(string[] args)
{
string json = "{\r\n \"Lines\": [\r\n {\r\n \"PropertyA\": \"A\",\r\n \"PropertyB\": \"B\"\r\n },\r\n {\r\n \"Property01\": 1,\r\n \"Property02\": 2\r\n }]\r\n}";
MainClass actual = JsonConvert.DeserializeObject<MainClass>(json);
MainClass expected = new MainClass()
{
Lines = new List<dynamic>()
{
new Class1(),
new Class2()
}
};
actual.Should().BeEquivalentTo(expected);
}
}
任何帮助将不胜感激!
干杯
【问题讨论】:
-
你的内部部分(propa、propb 和 prop1、prop2)将反序列化为 JSON 数组,而不是你可以反序列化为你想要的类的东西。您必须浏览数组并获取数据。
标签: c# json deserialization json-deserialization