I've done some googling but have not found an answer I'm satisfied with. I am currently learning C# and the .Net framework (I'm working as a fullstack-dev with Javascript/node) for fun, but I am not sure how you properly would go about parsing JSON from a http-request in the following structure:
{
"result": {
"data": {
"type": "articles",
"time": "05/27/2020",
"attributes": {
"timezone": "UTC",
"length": "3",
},
"articles": [
{ "type": "news", "created": "04/26/2019", "author": "Dohn Joe" },
{ "type": "news", "created": "04/26/2019", "author": "Dohn Joe" },
{ "type": "news", "created": "04/26/2019", "author": "Dohn Joe" }
]
}
}
}
I want to reach and use the articles array (maybe turn into a class that holds it / post to a database or something). Currently I get the http-request and then turn it into JSON
dynamic jsonResponse = JObject.Parse(result);
And then, in javascript you would normally do an if statement to kinda validate that you got the response you expected.
if (jsonResponse &&
jsonResponse.result &&
jsonResponse.result.data &&
jsonResponse.result.data.articles &&
jsonResponse.result.data.articles.length) {
//Parse the articles
}
I've read about ways in C# where you create "layered" classes that follows the strcuture of the JSON, and then just turn the entire response into a class/object. This feels weird since I am only interested in the articles-part and nothing else, so I want to check if the articles actually exists.
Is using the same if statement (more or less) to check for that a proper way of doing it in C#, or is there any other standard way of doing it that I have not read about yet? Or maybe the layered-class approach is most commonly used, just that it feels weird to me? But even If I turn it into a class/object, I would still need to verify that the items actually are there, right? I've also seen people just wrapping this in a try-catch and then trying to access the articles without if statements, letting the try-catch handle any problems. I'm a little confused from all the different answers I've read, whats the proper way of handling a json response from an http-request in this case?
Help is much appreciated! Thank you.