[英]Extract data from Json string
I got a string containing Json. 我有一个包含Json的字符串。 It looks like this:
它看起来像这样:
"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"
}
I am trying to get a hold of the "img_url". 我试图抓住“img_url”。 I have Json.NET installed and I´ve found similar questions here..
我安装了Json.NET,我在这里发现了类似的问题..
for example something like this: 例如这样的事情:
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");
In my case I changed ("People[0].Name")
to ("img_url")
, ("img_url[0])
etc..no luck 在我的情况下,我改变了
("People[0].Name")
到("img_url")
, ("img_url[0])
没有运气
This is my code now: 这是我现在的代码:
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;
}
}
Do I have to do something with the string before I can extract the value? 在提取值之前,我是否必须对字符串执行某些操作? Thanks!
谢谢!
img_url
is not a property of root object - it's a property of data
object: img_url
不是root对象的属性 - 它是data
对象的属性:
var obj = JObject.Parse(json);
var url = (string)obj["data"]["img_url"]; // http://s1.uploads.im/D9Y3z.png
Another option: 另外一个选项:
var url = (string)obj.SelectToken("data.img_url");
With help of this site 在这个网站的帮助下
var obj = JsonConvert.DeserializeObject<RootObject>(json);
Console.WriteLine(obj.data.img_url);
public class Data
{
public string img_name { get; set; }
public string img_url { get; set; }
public string img_view { get; set; }
public string img_width { get; set; }
public string img_height { get; set; }
public string img_attr { get; set; }
public string img_size { get; set; }
public int img_bytes { get; set; }
public string thumb_url { get; set; }
public int thumb_width { get; set; }
public int thumb_height { get; set; }
public string source { get; set; }
public string resized { get; set; }
public string delete_key { get; set; }
}
public class RootObject
{
public int status_code { get; set; }
public string status_txt { get; set; }
public Data data { get; set; }
}
You can also do the same thing with the use of dynamic
keyword (without declaring above classes) 你也可以使用
dynamic
关键字做同样的事情(不要声明上面的类)
dynamic obj = JsonConvert.DeserializeObject(json);
Console.WriteLine(obj.data.img_url);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.