【发布时间】:2010-11-15 12:49:21
【问题描述】:
List<User> list = LoadUsers();
JObject json = new JObject();
json["users"] = new JValue(list);
好像没用?
错误:
Could not determine JSON object type for type System.Collections.Generic.List`1
【问题讨论】:
List<User> list = LoadUsers();
JObject json = new JObject();
json["users"] = new JValue(list);
好像没用?
错误:
Could not determine JSON object type for type System.Collections.Generic.List`1
【问题讨论】:
JValue 只能包含简单的值,如字符串、整数、布尔值、日期等。它不能包含复杂的对象。我怀疑你真正想要的是这个:
List<User> list = LoadUsers();
JObject json = new JObject();
json["users"] = JToken.FromObject(list);
上面会将User 对象列表转换为代表用户的JObjects 的JArray,然后将其分配给新JObject 上的users 属性。您可以通过检查json["users"] 的Type 属性来确认这一点,看看它是Array。
相比之下,如果您按照此问题的另一个答案(现已删除)中的建议执行json["users"] = new JValue(JsonConvert.SerializeObject(list)),您可能不会得到您正在寻找的结果。该方法会将用户列表序列化为一个字符串,从中创建一个简单的JValue,然后将JValue 分配给JObject 上的users 属性。如果您检查json["users"] 的Type 属性,您将看到它是String。这意味着,如果您稍后尝试使用 json.ToString() 将 JObject 转换为 JSON,您将获得双序列化输出,而不是您可能期望的 JSON。
这里有一个简短的演示来说明区别:
class Program
{
static void Main(string[] args)
{
List<User> list = new List<User>
{
new User { Id = 1, Username = "john.smith" },
new User { Id = 5, Username = "steve.martin" }
};
JObject json = new JObject();
json["users"] = JToken.FromObject(list);
Console.WriteLine("First approach (" + json["users"].Type + "):");
Console.WriteLine();
Console.WriteLine(json.ToString(Formatting.Indented));
Console.WriteLine();
Console.WriteLine(new string('-', 30));
Console.WriteLine();
json["users"] = new JValue(JsonConvert.SerializeObject(list));
Console.WriteLine("Second approach (" + json["users"].Type + "):");
Console.WriteLine();
Console.WriteLine(json.ToString(Formatting.Indented));
}
class User
{
public int Id { get; set; }
public string Username { get; set; }
}
}
输出:
First approach (Array):
{
"users": [
{
"Id": 1,
"Username": "john.smith"
},
{
"Id": 5,
"Username": "steve.martin"
}
]
}
------------------------------
Second approach (String):
{
"users": "[{\"Id\":1,\"Username\":\"john.smith\"},{\"Id\":5,\"Username\":\"steve.martin\"}]"
}
【讨论】:
我遇到了这个问题,如果您只想要没有根名称的数组项,现在可以使用 JArray 来完成此操作。
var json = JArray.FromObject(LoadUsers());
如果希望json数组的根名称为“users”,可以使用
var json = new JObject { ["users"] = JToken.FromObject(LoadUsers()) };
【讨论】: