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".