【C#】Newtonsoft.Json 中 JArray 添加数组报错:Could not determine JSON object type for type 'xxx'

有时我们临时需要一个 JSON 字符串,直接拼接肯定不是好方法,但又懒得去定义一个类,这是用 JObject 就会非常的方便。

但是在 JObject 中添加数组却经常被坑。

List<string> names = new List<string>
{
    "Tom",
    "Jerry"
};

JArray array = new JArray(names);

JObject obj = new JObject()
{
    { "names", array }
};

Console.WriteLine(obj);

输出结果:

{
  "names": [
    "Tom",
    "Jerry"
  ]
}

非常正确,但如果把 List<string> 换成 List<class> 就不对了。

public class Person
{
    public int ID { get; set; }

    public string Name { get; set; }
}

List<Person> persons = new List<Person>
{
    new Person{ ID = 1, Name = "Tom" },
    new Person{ ID = 2, Name = "Jerry" }
};

JArray array = new JArray(persons);

JObject obj = new JObject()
{
    { "names", array }
};

Console.WriteLine(obj);

这么写会报:Could not determine JSON object type for type 'xxx'

这是由于自定义类不属于基本类型所致。这是就只能用 JArray.FromObject

JObject obj = new JObject()
{
    { "persons", JArray.FromObject(persons) }
};

序列化结果就正确了。

{
  "names": [
    {
      "ID": 1,
      "Name": "Tom"
    },
    {
      "ID": 2,
      "Name": "Jerry"
    }
  ]
}
posted @ 2020-04-03 13:04  丹枫无迹  阅读(1609)  评论(0编辑  收藏  举报