I am not sure how frequently you come across situation where you need to deserialize a response object of a rest API in C#, but I come across it quite frequently. I did lots of search to figure out the concrete answer, I couldn’t find anything that answered my requirement. After spending some time (quite a more time) finally I was able to deserialize response object according to my requirement.
Hence, thought to share it with you all1 and contribute in saving you precious time.
Requirement:
I had following object as response in JSON format:
As you can see in above document, my need was to access the value of key “thirdLevelKey4”. I did try lots of solutions which I found in google, and was able to access only ‘firstLevelKeys’ and ‘secondLevelKeys’ but not the ‘thirdLevelKeys’.
Finally, I could do it as follows:
I have written a small console application for the demo.
- First, create the class with API call as below.
So, as mentioned in the above image ‘respStr’ contains the response as “"{\"firstLevelKey1\":\"firstLevelValue1\",\"firstLevelKey3\":firstLevelValue3,\"firstLevelKey4\":firstLevelValue4,\"firstLevelKey2\":[{\"secondLevelKey1\":\"secondLevelValue1\".....]}"” which we can’t consume/parse it directly to reach the ‘thirdLevelKey’.
- Add the classes below to main class.
Now, as we know the JSON structure, create the object class which will help to parse each level one by one.
This will initialize the value of key which we need.
public class requiredField
{
public string thirdLevelKey4 { get; set; }
}
But, this is not enough to reach there directly. We need parse it step by step. Hence create a class to read the parent of this key. Something like below:
public class parentOfrequiredField
{
public object secondLevelKey2 { get; set; }
}
Repeat the same step till the JSON root element.
public class rootElement
{
public List<parentOfrequiredField> firstLevelKey2 { get; set; }
}
Then start parsing one by one in the main class as below:
var testData = JsonConvert.DeserializeObject< rootElement >(respStr);
foreach (var childItem in testData.firstLevelKey2) {
var requiredData = JsonConvert.DeserializeObject<requiredField>(childItem.secondLevelKey2.ToString());
}
So, we got the required data in variable ‘requiredData’.
Below the complete code for reference:
Please like and leave your comments below to improve the post.
Thanks,
Naveen