Extract data from Json string

前端 未结 2 453
陌清茗
陌清茗 2020-12-02 21:07

I got a string containing Json. It looks like this:

\"status_code\":200,
\"status_txt\":\"OK\",
\"data\":
{
   \"img_name\":\"D9Y3z.png\",
   \"img_url\":\"h         


        
相关标签:
2条回答
  • 2020-12-02 21:43

    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 obj = JsonConvert.DeserializeObject(json);
    Console.WriteLine(obj.data.img_url);
    
    0 讨论(0)
  • 2020-12-02 21:48

    img_url is not a property of root object - it's a property of data object:

    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");
    
    0 讨论(0)
提交回复
热议问题