简体   繁体   中英

Accessing a certain variable inside a json without creating a deserialization class

I currently have a json string that looks like this

{ 
   "strA":"somestr",
   "strB":{ 
      "strB":"String B",
      "strC":"String C",
      "sections":[ 
         { 
            "strD":"...",
            "str$":"...",
            "myArray":[ 
               { 
                  "name":"xxxx",
                  "value":"xxxx"
               }
            ]
         }
      ]
   }
}

Now the content of this json could change however strB will always be where it is. The value of strB can always change. I would like to get the value of strB as string. I tried doing this

var info = JsonConvert.DeserializeObject<Dictionary<string, dynamic>>(str);
string strB = info["strB"].ToString();

but that seems to be wrong . Any idea on how I can extract strB value from this json as a string without creating a deserialization class .

You can use JObject and run linq on it.

 JObject json = JObject.Parse(jsonstring);
 // access the value like this
 json["strB"]

Find some very good example: https://www.newtonsoft.com/json/help/html/QueryingLINQtoJSON.htm

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM