【问题标题】:C# JSON Deserialization Dictionary ExceptionC# JSON 反序列化字典异常
【发布时间】:2015-11-12 09:44:01
【问题描述】:

我需要 C# 中的 JSON 解析方面的帮助。我正在尝试解析和使用我的 JSON 字符串。我不想创建一个类来实例化对象,因为可以有更多的调用,返回对象类型很多 - 锦标赛、团队、用户等。

{
    "response":{
        "2":{
            "tournament_id":2,
            "created_at":{
                "date":"2015-11-09 21:01:06",
                "timezone_type":3,
                "timezone":"Europe/Prague"
            },
            "creator_id":1,
            "name":"Tournament Test #1",
            "desc":"...!",
            "state":0,
            "is_visible":1
        },
        "3":{
            "tournament_id":3,
            "created_at":{
                "date":"2015-11-09 21:01:06",
                "timezone_type":3,
                "timezone":"Europe/Prague"
            },
            "creator_id":1,
            "name":"Tournament Test #2",
            "desc":"...",
            "state":1,
            "is_visible":1
        }
    },
    "error":false
}

我正在使用 JSON.net 库来解析 JSON 字符串,这是我在程序中使用的 C# 代码:

public class API
    {
        private WebClient client;

        protected string auth_key   = "xxx";
        protected string base_url   = "http://127.0.0.1/tournaments_api/www/";
        private string endpoint_url = "";
        private string url_params   = "";

        public string url_data;
        public Dictionary<string, string>[] data;

        public bool success = false;
        public string errorMessage = "";
        public int errorCode = 0;

        public API()
        {
            this.client = new WebClient();
        }

        private void Request()
        {

            string url = this.base_url + this.endpoint_url + "/" + this.auth_key + "?" + this.url_params;
            this.url_data = this.client.DownloadString(url);
            Console.WriteLine(this.url_data);

            this.data = JsonConvert.DeserializeObject<Dictionary<string, string>[]>(this.url_data);
        }
    }

解析有这个问题:

未处理的类型异常 'Newtonsoft.Json.JsonSerializationException' 发生在 Newtonsoft.Json.dll

附加信息:无法反序列化当前 JSON 对象 (例如 {"name":"value"}) 转换为类型 'System.Collections.Generic.Dictionary`2[System.String,System.String][]' 因为该类型需要一个 JSON 数组(例如 [1,2,3])来反序列化 正确。

要修复此错误,请将 JSON 更改为 JSON 数组(例如 [1,2,3]) 或更改反序列化类型,使其成为普通的 .NET 类型(例如,不是像整数这样的原始类型,不是集合类型 像数组或列表)可以从 JSON 对象反序列化。 JsonObjectAttribute 也可以添加到类型中以强制它 从 JSON 对象反序列化。

路径“响应”,第 1 行,位置 12。

感谢您的帮助! :)

【问题讨论】:

  • 您的 JSON 中绝对没有数组。

标签: c# dictionary serialization json.net


【解决方案1】:

您的 JSON 是一个对象,在 C# 中可以反序列化为 Dictionary&lt;string, object&gt;。但是,您尝试将其反序列化为数组,而绝对没有数组。

您需要将其更改为:

public Dictionary<string, object>[] data;

// ...

JsonConvert.DeserializeObject<Dictionary<string, object>>(this.url_data);

同时,即使更改后,您也无法访问嵌套对象。

在你写的时候

我不想创建一个类来实例化对象,因为可能会有更多的调用,返回对象类型很多 - 锦标赛、团队、用户等。

我可能建议使用dynamic:

dynamic data = JsonConvert.DeserializeObject(this.url_data);

然后,您将能够像使用动态对象一样使用它:

var err = data.error;

同时,创建一个类来描述这个模型并用于反序列化这个 JSON 对我来说听起来更好。

【讨论】:

    【解决方案2】:

    Yeldar Kurmangaliyev 的替代方案是使用 JSON.NET 库的内置 LINQ to JSON 支持:

    JObject jObject = JObject.Parse("-- JSON STRING --");
    
    JToken response = jObject["response"];
    
    bool error = jObject["error"].Value<bool>();
    

    有很多扩展方法可以轻松解析json字符串。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-08-22
      • 1970-01-01
      • 2023-01-09
      • 2019-10-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多