3

My problem is that I am trying to parse an unknown block of json and look for the value of a specific property. I have the path to the particular property and its name, and that is all I know.

Let's say my JSON is this:

{
    "firstName": "John",
    "lastName": "Smith",
    "age": 25,
    "address": {
        "streetAddress": "21 2nd Street",
        "city": "New York",
        "state": "NY",
        "postalCode": 10021
    },
}

The user would pass me the string address.city and expect to be returned the string New York. However, remember, I don't have any knowledge of the object in the first place, so I can't just simply parse the JSON directly into a known object container.

Here's what I've tried, using JSON.NET. Note, I'm not married to this solution, I just want a solution that solves the problem.

string propertyName = "address.city";
string responseBody= // assume JSON above is here properly formatted
JObject parsedResponseBody = JObject.Parse(responseBody);
string[] parsedPropertyName = propertyName.Split('.');

var foundValue = parsedResponseBody.GetValue(parsedPropertyName[0]);
for (int index = 1; index < parsedPropertyName.Count(); index++)
{
    foundValue = foundValue.getValue(parsedPropertyName[index]);
}

Unfortunately, this falls apart because the first GetValue() returns a JToken, and not another JObject like I had hoped and I can't find in the documentation where I can specifically access a specific property, just the bulk JSON.

Alternatively, in JSON.NET documentation, the "Querying JSON" examples look like they would solve my problem, except I don't know how to generate something like blogPost.Author.Name from its string representation.

Thanks in advance for any help.

Edit: Okay, so I wasn't quite clear enough in the original post, judging from some of the answers. Not only is the response JSON object unknown, but I can't rely on the propertyName field only being two pieces. It can be something like "prop1.prop2.prop3.prop4" or as simple as "prop1".

3 Answers 3

7

You can try following sample:

var jObj = JObject.Parse(jsonString);
var token = jObj.SelectToken(propertyName);

assuming that jsonString variable is any json string and propertyName is any path you want to get.

Sign up to request clarification or add additional context in comments.

1 Comment

The code above will work even if your propertyName is something like prop1.prop2.prop3.prop41 or simply prop1. As soon as you know the path, you can get it with this code sample.
1

Here's some code I use to enumerate over keys in a JSON string:

private Dictionary<string, object> JSONToDictionary(string jsonString)
{
    var jObj = (JObject)JsonConvert.DeserializeObject(jsonString);
    var dict = JsonConvert.DeserializeObject<Dictionary<string, object>>(jObj.ToString());

    return dict;
}

And then in your code:

foreach (KeyValuePair<string, object> kvp in JSONToDictionary("{ \"some\": \"jsonfile\" }"))
{
    // (kvp.Key == "some") = true
    // ((kvp.Value as string) == "jsonfile") = true
}

4 Comments

Won't this then require a parse of the values to get their child properties? See edit please.
Yes, if the value is another JSON object, you will need to detect that and parse it in the same way. There has to be some give with respect to knowing the JSON format. Why would you be attempting to format JSON structures you know absolutely nothing about anyway?
Because that's what the problem is? My users have a problem where they want to format JSON structures that they don't want to have to take the time to tell me about.
You can use the code I provided to get each entry from a foreach loop, it will give you the name of the entry and the data attached to it. You don't have to know anything about the structure for this to work. Isn't that what you wanted?
1
IDictionary<string, JToken> Jsondata = JObject.Parse(yourJsonString);
        foreach (KeyValuePair<string, JToken> element in Jsondata) {
            string innerKey = element.Key;
            if (element.Value is JArray) {
                // Process JArray
            }
            else if (element.Value is JObject) { 
                // Process JObject
            }
        }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.