Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get list of objects from json string c# Newtonsoft.json

Tags:

json

c#

json.net

I am trying to convert a JSON string into a list of objects but am getting the error

Cannot deserialize the current JSON object into type List because the type requires a JSON array to deserialize correctly.

I retrieve the json and it looks like this

{
    "Code":0,
    "Message":"OK",
    "Data":
    {
        "Houses":
        [
            {
                "Id":1,
                "Name":"House 1",
                "Area":"22.00",
                "ShortName":"H1",
                "FarmName":"Farm 1"
            },
            {
                "Id":2,
                "Name":"Farmi1 - House 1",
                "Area":"1000.00",
                "ShortName":"H1",
                "FarmName":"Farm 1"
            }
        ]
    }
}

I then say

List<House> Houses = JsonConvert.DeserializeObject<List<House>>(json); 
like image 826
Michael Grinnell Avatar asked Mar 06 '23 21:03

Michael Grinnell


1 Answers

The JSON string you get is not a list, but an object which has a list on a nested level. You will have to deserialize the outermost structure and then get the respective nested property.

You can either define a whole class representing the complete structure of your data, or, if you are only interested in the List of Houses, just use JObjects

var o = JsonConvert.DeserializeObject<JObject>(json);
var h = o.Value<JObject>("Data")
    .Value<JArray>("Houses")
    .ToObject<List<Houses>>();
like image 104
derpirscher Avatar answered Mar 23 '23 20:03

derpirscher