【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"
    }
  ]
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章