VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > Python基础教程 >
  • 【C#】Newtonsoft.Json 中 JArray 添加数组报错:Could not determine JSON object type for type

有时我们临时需要一个 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"
    }
  ]
}

相关教程