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

Can Json.Net handle a Listlt;objectgt;?(Json.Net 可以处理 Listlt;objectgt; 吗?)
本文介绍了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; 吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

Force JsonConvert.SerializeXmlNode to serialize node value as an Integer or a Boolean(强制 JsonConvert.SerializeXmlNode 将节点值序列化为整数或布尔值)
Using JSON to Serialize/Deserialize TimeSpan(使用 JSON 序列化/反序列化 TimeSpan)
Could not determine JSON object type for type quot;Classquot;(无法确定类型“Class的 JSON 对象类型.)
How to deserialize a JSONP response (preferably with JsonTextReader and not a string)?(如何反序列化 JSONP 响应(最好使用 JsonTextReader 而不是字符串)?)
how to de-serialize JSON data in which Timestamp it-self contains fields?(如何反序列化时间戳本身包含字段的JSON数据?)
JSON.Net custom contract serialization and Collections(JSON.Net 自定义合约序列化和集合)