【发布时间】:2015-09-03 14:55:56
【问题描述】:
我有一个关于反序列化 json 数据的问题。我的json数据是这样的
{
"batchcomplete": "",
"query": {
"pages": {
"62413": {
"pageid": 62413,
"ns": 0,
"title": "espri"
}
}
}
}
我想获取页面 ID 或仅获取数字。数字“62413”正在改变每个不同的请求。
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public void readString()
{
requestHelper _req = null;
HttpClient client = new HttpClient();
HttpResponseMessage response = client.GetAsync("https://tr.wiktionary.org/w/api.php?action=query&titles=espri&format=json").Result;
//var categories = new object { };
if (response.IsSuccessStatusCode)
{
var content = response.Content.ReadAsStringAsync().Result;
//categories = response.Content.ReadAsStringAsync();
//dynamic a = JsonConvert.DeserializeObject(content);
//Dictionary<string, object> dict = JsonConvert.DeserializeObject<Dictionary<string, object>>(content);
var b = JObject.Parse(content).Descendants().ToArray();
var art = b[9];
_req = new requestHelper { _result = 1, _message = content };
}
HttpContext.Current.Response.Write(new JavaScriptSerializer().Serialize(_req));
}
}
我的代码是这样的,这解决了我的问题,但我认为这不是最好的方法。我的问题是有什么不同的方法可以得到我想要的吗?我尝试使用字典,但我无法弄清楚。感谢您的帮助。
【问题讨论】:
-
Eser 是对的,做一个模型。一些想法: JsonConvert 有点慢,您可能要考虑 newtonsoft 当您的响应不成功时,我看到一个空引用异常(_req 将为 null ),我建议将
HttpContext.Current.Response.Write(new JavaScriptSerializer().Serialize(_req));放在 if 语句中. -
感谢您的评论我只是想获取数据,所以之后我会重新排列我的代码,但再次感谢您