0

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.

JohnyL
  • 6,894
  • 3
  • 22
  • 41
  • 2
    Have you looked at https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-how-to – Raju Joseph May 27 '20 at 05:56
  • 1
    C# is a statically typed language and in my opinion the use of `dynamic` in C# is an anti-pattern. I recommend you take a look at the official [Microsoft documentation](https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-how-to) on the subject and implement a class to directly deserialize to – MindSwipe May 27 '20 at 05:59
  • And while we do apreciate a class to map the object. As json is just a serialisation of an object. We do not need to have of the hierachy. you can just deserialise the part you need https://www.newtonsoft.com/json/help/html/SerializingJSONFragments.htm – xdtTransform May 27 '20 at 06:17
  • note that the generation of the class is nothing more than a copy past in the editor. So there is no time lost in the definition of the object. https://stackoverflow.com/questions/21611674/how-to-auto-generate-a-c-sharp-class-file-from-a-json-string – xdtTransform May 27 '20 at 06:21
  • https://www.newtonsoft.com/json/help/html/SerializingJSONFragments.htm – Jeremy Lakeman May 27 '20 at 10:45

1 Answers1

0

You can convert JSON to a List / ViewModel in C# / ASP.NET MVC as shown below:

public ActionResult Save(string json)
{ 
  IList<DemoViewModel> model = new
      JavaScriptSerializer().Deserialize<IList<DemoViewModel>>(json);

  //or

  List<DemoViewModel> model = new 
      JavaScriptSerializer().Deserialize<List<DemoViewModel>>(json);
}

You may pass data to be converted Json via Ajax as shown below:

$.ajax({
  type: "POST",
  url: '@Url.Action("Save", "DemoContoller")',
  cache: false,
  dataType: "json",
  data: { json: JSON.stringify(demoData), "__RequestVerificationToken": $('input[name=__RequestVerificationToken]').val() },

  //...
});
Murat Yıldız
  • 11,299
  • 6
  • 63
  • 63