Pratik Mehta
Pratik Mehta

Reputation: 1352

Access property from JSON string where parent object name is not fixed

I have the following JSON string, and I need to access the property value named "Mode" from it:

{
  "CommomData": {
    "DateTime": {
      "Year": 2019,
      "Month": 3,
      "Day": 11,
      "Hour": 14,
      "Min": 1,
      "Second": 29
    }
  },
  "Status": {
    "Mode": "Test",
    "Loc": "Test"
  }
}

If you note here, the parent property name for "Mode", here is "Status" but this could change to "LatestStatus" or "FirstStatus" or any other value.

Currently, I have written the code below and it works fine, but it takes around 60 to 150 milliseconds for the operation (we want to reduce this time). Please note that the object has many more properties, but I only posted a few to explain the issue.

Is there any other optimal way to get the value from the JSON string without knowing the object type and the parent property name?

JObject payloadJObject = JObject.Parse(payload);

foreach (var item in payloadJObject)
{
    foreach (JProperty subitem in item.Value.ToList())
    {
        if (subitem.Name == "Mode")
        {
            return Convert.ToString(subitem.Value);
        }
    }
}

Upvotes: 0

Views: 807

Answers (1)

Brian Rogers
Brian Rogers

Reputation: 129727

Depending on your definition of "optimal":

The shortest way to find a property somewhere in the JSON is to parse the JSON to a JObject and then use SelectToken with a recursive descent JsonPath expression:

public static string FindFirst(string json, string propertyName)
{
    return JObject.Parse(json).SelectToken("$.." + propertyName)?.ToString();
}

Fiddle: https://dotnetfiddle.net/JQxu9c

The fastest way that I know of to do the same thing with Json.Net is to use a JsonTextReader:

public static string FindFirst(string json, string propertyName)
{
    using (StringReader sr = new StringReader(json))
    using (JsonReader reader = new JsonTextReader(sr))
    {
        while (reader.Read())
        {
            if (reader.TokenType == JsonToken.PropertyName && 
                reader.Value.ToString() == propertyName)
            {
                return reader.ReadAsString();
            }
        }
        return null;
    }
}

Fiddle: https://dotnetfiddle.net/aR3qVe

Upvotes: 2

Related Questions