【发布时间】: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