当前位置: 移动技术网 > IT编程>开发语言>c# > 【C#】Newtonsoft.Json 中 JArray 添加数组报错:Could not determine JSON object type for type 'xxx'

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

2020年04月03日  | 移动技术网IT编程  | 我要评论

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

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网