【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 @   丹枫无迹  阅读(1681)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· 展开说说关于C#中ORM框架的用法!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
点击右上角即可分享
微信分享提示