C# get name of the JSON object

Viewed 40

I´ve got a JSON stored in a string named resultString it looks like this:

{"BRC1": {"image": "9b.jpg", "query": "led", "status": "ok", "data": {"value": {"LED_1": "OFF", "LED_2": "OFF", "LED_3": "OFF", "LED_4": "RED", "LED_5": "RED", "SILA": "ON", "ASLED": "ORANGE"}}}}

Now I want to get the value "BRC1" as string. I tried this:

var data = (JObject)JsonConvert.DeserializeObject(resultString);
string resdevname = data["BRC1"].Value<string>();

also tried:

string resdevname = data[BRC1].Value<string>();

But I always get an Exception:

System.InvalidCastException: Cannot cast Newtonsoft.Json.Linq.JObject to Newtonsoft.Json.Linq.JToken.

what am I doing wrong?

2 Answers

If you just want "the name of the first property in the object" then you can use:

var data = (JObject)JsonConvert.DeserializeObject(resultString);
IEnumerable<KeyValuePair<string, JToken>> pairs = data;
string firstName = pairs.FirstOrDefault().Name;

firstName will be null if the object is actually empty.

if you need just BRC1 value as a json string and you don't know a root property name try this

string rootName = JObject.Parse(json).Properties().First().Name; // "BRC1"
    
string  rootJson = JsonConvert.SerializeObject (JsonConvert.DeserializeObject<JObject>(rootJson));

result

{"image":"9b.jpg","query":"led","status":"ok","data":{"value":{"LED_1":"OFF","LED_2":"OFF","LED_3":"OFF","LED_4":"RED","LED_5":"RED","SILA":"ON","ASLED":"ORANGE"}}}

or if you want it as escaped string

var rootJsonEscaped = JsonConvert.SerializeObject(rootJson)

result

"{\"image\":\"9b.jpg\",\"query\":\"led\",\"status\":\"ok\",\"data\":{\"value\":{\"LED_1\":\"OFF\",\"LED_2\":\"OFF\",\"LED_3\":\"OFF\",\"LED_4\":\"RED\",\"LED_5\":\"RED\",\"SILA\":\"ON\",\"ASLED\":\"ORANGE\"}}}"

or if you want it formatted

string rootJson = JObject.Parse(json).Properties().First().Value.ToString();

result

{
  "image": "9b.jpg",
  "query": "led",
  "status": "ok",
  "data": {
    "value": {
      "LED_1": "OFF",
      "LED_2": "OFF",
      "LED_3": "OFF",
      "LED_4": "RED",
      "LED_5": "RED",
      "SILA": "ON",
      "ASLED": "ORANGE"
    }
  }
}
Related