简体   繁体   中英

Deserialize Json into C# Collection

I want to deserialize json into collection of C# objects but getting following error:

{"Cannot deserialize the current JSON object (eg {\\"name\\":\\"value\\"}) into type 'System.Collections.Generic.List`1 because the type requires a JSON array (eg [1,2,3]) to deserialize correctly.\\r\\nTo fix this error either change the JSON to a JSON array (eg [1,2,3]) or change the deserialized type so that it is a normal .NET type (eg not a primitive type like integer, not a collection type like an array or List) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.\\r\\nPath 'organizations', line 1, position 17."}

Code:

 var jSon = "{\"Houses\":[{\"id\":\"123\",\"doorNumber\":22},
                          {\"id\":\"456\",\"deniNumber\":99}
            ]}";
        var temp = JsonConvert.DeserializeObject<List<House>>(jSon);
    }


public class House
{
    public int Id { get; set; }

    public int DoorNumber { get; set; }
}

The JSON you've shown is an Object with a Property called Houses that contains your array. Note how the outer Json is surrounded by { } and not [ ] which is why you're seeing that error. You'll need to select only the value of that property if you want to deserialize to a list of House. You can do that using JObject and then selecting the Houses property specifically.

var jobj = JObject.Parse(jSon);
var houses = JsonConvert.DeserializeObject<List<House>>(jobj["Houses"].ToString());

Alternatively you could do:

var houses = JObject.Parse(jSon)["Houses"].ToObject<List<House>>();

If you want to be able to map it in one step without using JObject you'd have to have another class that wraps your House list and maps directly to the JSON you've shown.

public class HouseList
{
    public List<House> Houses {get; set;}
}

Given this object you'd be able to do

var houses = JsonConvert.DeserializeObject<HouseList>(jSon).Houses;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM