Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deserializing JSON response without creating a class

Tags:

json

c#

From the result of an API call I have a large amount of JSON to process.

I currently have this

Object convertObj = JsonConvert.DeserializeObject(responseFromServer);

I am aware that I could do something like

Movie m = JsonConvert.DeserializeObject<Movie>(responseFromServer);

And then use it like

m.FieldName
m.AnotherField
//etc

Ideally I would like to do something like

var itemName = convertObj["Name"];

to get the first Name value for the first item in the list.

Is this possible, or do I have to create a class to deserialize to?

The reason I do not want to create the class is I am not the owner of the API and the field structure may change.

Edit.

Okay so I created the class as it seems the best approach, but is there a way to deserialize the JSON into a list?

var sessionScans = new List<SessionScan>();
sessionScans = JsonConvert.DeserializeObject<SessionScan>(responseFromServer);

Complains that it cannot convert SessionScan to generic list.

like image 752
andrewb Avatar asked Nov 22 '16 04:11

andrewb


2 Answers

No need to use dynamic, you can simply use JToken which is already does what you expect:

var json = @"
    {
        ""someObj"": 5
    }
";
var result = JsonConvert.DeserializeObject<JToken>(json);
var t = result["someObj"]; //contains 5
like image 189
Rob Avatar answered Sep 29 '22 08:09

Rob


You can try with JObject.Parse :

dynamic convertObj = JObject.Parse("{ 'Name': 'Jon Smith', 'Address': { 'City': 'New York', 'State': 'NY' }, 'Age': 42 }");

string name = convertObj.Name;
string address = convertObj.Address.City;
like image 37
Yanga Avatar answered Sep 29 '22 07:09

Yanga