有時我們臨時需要一個 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"
}
]
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/56695.html
標籤:C#
