【发布时间】:2014-06-15 19:06:55
【问题描述】:
我得到了一个包含 Json 的字符串。它看起来像这样:
"status_code":200,
"status_txt":"OK",
"data":
{
"img_name":"D9Y3z.png",
"img_url":"http:\/\/s1.uploads.im\/D9Y3z.png",
"img_view":"http:\/\/uploads.im\/D9Y3z.png",
"img_width":"167",
"img_height":"288",
"img_attr":"width=\"167\" height=\"288\"",
"img_size":"36.1 KB",
"img_bytes":36981,
"thumb_url":"http:\/\/s1.uploads.im\/t\/D9Y3z.png",
"thumb_width":360,
"thumb_height":360,
"source":"http:\/\/www.google.com\/images\/srpr\/nav_logo66.png",
"resized":"0",
"delete_key":"df149b075ab68c38"
}
我正在尝试获取“img_url”。我已经安装了 Json.NET,我在这里发现了类似的问题..
例如这样的:
JObject o = JObject.Parse("{'People':[{'Name':'Jeff'},{'Name':'Joe'}]}");
// get name token of first person and convert to a string
string name = (string)o.SelectToken("People[0].Name");
在我的情况下,我将 ("People[0].Name") 更改为 ("img_url")、("img_url[0]) 等......没有运气
这是我现在的代码:
public string tempJson { get; set; }
public ActionResult SaveUploadedFile(string test)
{
using (WebResponse wrs = wrq.GetResponse())
using (Stream stream = wrs.GetResponseStream())
using (StreamReader reader = new StreamReader(stream))
{
string json = reader.ReadToEnd();
tempJson = json;
}
}
在提取值之前,我是否必须对字符串进行处理? 谢谢!
【问题讨论】:
-
仔细查看您的 JSON。 “img_url”属性是 JSON 对象的一部分,该对象再次分配给 JSON 属性。该属性的名称是什么?
-
你是说数据?我迷路了?
-
是的,“数据”。因此你应该使用
SelectToken("data.img_url"); -
现在感觉很傻......尝试了很多组合但没有这个......谢谢!
-
我正在写答案。马克谢尔盖的回答,很好。但是请注意一些差异:如果“数据”对象不在您的 JSON 中,Sergey 的代码将抛出异常,而 SelectToken 只会返回 null(不确定这是否与您的应用场景相关)