简体   繁体   English

将Json反序列化为C#集合

[英]Deserialize Json into C# Collection

I want to deserialize json into collection of C# objects but getting following error: 我想反序列化json到C#对象的集合中,但是出现以下错误:

{"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."} {“无法反序列化当前JSON对象(例如{\\” name \\“:\\” value \\“})为类型'System.Collections.Generic.List`1,因为该类型需要JSON数组(例如[1,2, 3])正确反序列化。\\ r \\ n要解决此错误,请将JSON更改为JSON数组(例如[1,2,3])或更改反序列化的类型,使其成为普通的.NET类型(例如,非可以从JSON对象反序列化的基本类型(例如整数),而不是可以从JSON对象反序列化的集合类型(例如数组或List);也可以将JsonObjectAttribute添加到该类型中,以强制其从JSON对象反序列化。第1行,位置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. 您显示的JSON是一个具有名为Houses的属性的对象,其中包含您的数组。 Note how the outer Json is surrounded by { } and not [ ] which is why you're seeing that error. 请注意,外部Json是如何用{ }而不是[ ]包围的,这就是为什么您看到该错误的原因。 You'll need to select only the value of that property if you want to deserialize to a list of House. 如果要反序列化为House列表,则只需选择该属性的值。 You can do that using JObject and then selecting the Houses property specifically. 您可以使用JObject,然后专门选择Houses属性来实现。

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. 如果您希望能够在不使用JObject的情况下一步对其进行映射,则必须具有另一个包装House列表并将其直接映射到所显示的JSON的类。

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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