打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
【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"    }  ]}
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
C#
C# 操作JSON的几种方式
Json.Net系列教程 4.Linq To JSON
JSON转换
Android系统移植与平台开发- JNI介绍
Newtonsoft.Json解析数组的小例子
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服