Rizwan
Rizwan

Reputation: 89

Working with JSON in C# ASP NET Core without deserialization

I would like to know if there is a quicker and direct way to read and write in C# ASP NET Core without having to create classes of JSON data models.

Consider the following JSON data received from an API. Is there a way to read fields as strings directly without having to deserialize them using JsonSerializer?

{
  "data": [
    {
      "id": "100285832430"
    },
    {
      "id": "102602230220"
    }
  ],
  "paging": {
    "cursors": {
      "before": "MTAwMTIxMDMyNDMw",
      "after": "MTAyNjY4NzAyMjIw"
    }
  }
}

Thank you

Upvotes: 0

Views: 1406

Answers (1)

sommmen
sommmen

Reputation: 7628

You can very easily copy some json text and then translate it to a model.

enter image description here

Or use something like http://www.quicktype.io

You can also use an anonymous object:

https://www.newtonsoft.com/json/help/html/DeserializeAnonymousType.htm

Or even a dynamic

https://stackoverflow.com/a/63457332/4122889

Btw, You can also read partial json if you're dealing with large datasets:

https://www.newtonsoft.com/json/help/html/SerializingJSONFragments.htm

I gues you could also use regex to parse the string or write custom logic - but ofcourse i would not recommend that.

For example: \"id\": \"([0-9]*)\" to get all id's.

This however is not faster for development and i doubt it'll be faster for the app. Just stick with models and json. I'm not sure about your setup but perhaps there are things to automate if you have a lot of models?

Upvotes: 1

Related Questions