Json.Net 可以处理 List<object> 吗?

时间:2023-04-25
本文介绍了Json.Net 可以处理 List<object> 吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

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 只能包含简单的值,如字符串、整数、布尔值、日期等.它不能包含复杂的对象.我怀疑你真正想要的是这个:

A JValue can only contain simple values like strings, ints, booleans, dates and the like. It cannot contain a complex object. I suspect what you really want is this:

List<User> list = LoadUsers();

JObject json = new JObject();

json["users"] = JToken.FromObject(list);

上面会将 User 对象的列表转换为代表用户的 JObjectsJArray,然后将其分配给 JObject 上的 users 属性.您可以通过检查 json["users"]Type 属性来确认它是 Array.

The above will convert the list of User objects into a JArray of JObjects representing the users, then assign that to the users property on the new JObject. You can confirm this by examining the Type property of json["users"] and see that it is Array.

相比之下,如果您按照此问题的另一个答案(现已删除)中的建议执行 json["users"] = new JValue(JsonConvert.SerializeObject(list)),您可能会没有得到你正在寻找的结果.该方法会将用户列表序列化为一个字符串,从中创建一个简单的 JValue,然后将 JValue 分配给 users 属性JObject.如果您检查 json["users"]Type 属性,您将看到它是 String.这意味着,如果您稍后尝试使用 json.ToString()JObject 转换为 JSON,您将获得双序列化输出而不是您可能的 JSON期待.

In contrast, if you do json["users"] = new JValue(JsonConvert.SerializeObject(list)) as was suggested in another answer to this question (now deleted), you will probably not get the result you are looking for. That approach will serialize the list of users to a string, create a simple JValue from that, and then assign the JValue to the users property on the JObject. If you examine the Type property of json["users"], you will see that it is String. What this means is, if you later try to convert the JObject to JSON by using json.ToString(), you will get double-serialized output instead of the JSON you probably expect.

这里有一个简短的演示来说明区别:

Here is a short demo to illustrate the difference:

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"}]"
}

这篇关于Json.Net 可以处理 List&lt;object&gt; 吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一篇:JSON.NET JObject - 我如何从这个嵌套的 JSON 结构中获取价值 下一篇:Json.Net 和 ActionResult

相关文章