Search code examples
c#jsonjson.net

C# get name of the JSON object


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.


Solution

  • 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"
        }
      }
    }