C#JSON反序列化字典异常
本文关键字:异常 字典 反序列化 C#JSON | 更新日期: 2023-09-27 18:21:34
我需要帮助在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类型(例如,不是像integer这样的基元类型,不是集合类型像数组或列表),可以从JSON对象反序列化。JsonObjectAttribute也可以添加到类型中,以强制它从JSON对象反序列化。
路径"响应",第1行,位置12。
谢谢你的帮助!:)
JSON是一个对象,在C#中可以反序列化为Dictionary<string, object>
。然而,您尝试将其反序列化为数组,而绝对没有数组。
您需要将其更改为:
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对我来说更好
Yeldar Kurmangaliyev的答案的替代方案是使用JSON.NET库的内置LINQ到JSON支持:
JObject jObject = JObject.Parse("-- JSON STRING --");
JToken response = jObject["response"];
bool error = jObject["error"].Value<bool>();
有很多扩展方法可以方便地解析json字符串。