Search code examples
c#.netjsonjson.netdynamicobject

How do I call an object property with empty property name?


I have the following JSON and I have no control over it since it comes from an external API:

    {
  "user_id": "something_name",
  "devices": {
    "": {
      "sessions": [
        {
          "connections": [
            {
              "ip": "225.225.225.225",
              "user_agent": "something",
              "last_seen": 1504266816737
            }
        }
      ]
    }
  }
}

I am using a JSON deserializer(JSON.Net) to make it into a dynamic object.

dynamic values = JsonConvert.DeserializeObject<dynamic>(mes);

The thing is, one of the json key is an empty string "". Now I can't seem to call the property as such:

values.devices.<the empty string part>.sessions.connections

How do I call things below it when one of the top key is empty? Doing devices..sessions did not work.


Solution

  • You can use square bracket syntax to access the property with the empty key. For example:

    dynamic ip = values.devices[""].sessions[0].connections[0].ip;
    

    Fiddle: https://dotnetfiddle.net/H4orMZ