简体   繁体   English

无法将JSON数组反序列化为C#列表

[英]Not able to deserialize JSON array into C# list

I have a json array as below 我有一个JSON数组如下

{
"odata.metadata": "https://testapp.mycomp.com/$metadata#UnitDetail",
"value": [
    {
        "Id": 1,
        "UnitId": 238905,
        "Active": false,
        "Name": "Rakesh",
        "ContactNumber": "0070002934"           
    },
    {
        "Id": 2,
        "UnitId": 238906,
        "Active": true,
        "Name": "Rahul",
        "ContactNumber": "123444003"
    },
    {
        "Id": 3,
        "UnitId": 238907,
        "Active": true,
        "Name": "Rohit",
        "ContactNumber": "1227032932"
    }
]

} }

I am trying to deserialize it into c# list as below 我正在尝试将其反序列化为c#列表,如下所示

 var data= JsonConvert.DeserializeObject<UnitDetail[]>(json);

My c# class is a below 我的C#课程在下面

  public class UnitDetail
{
    public int Id { get; set; }
    public int UnitId { get; set; }
    public bool Active { get; set; }
    public string Name { get; set; }
    public string ContactNumber { get; set; }

}

But this code is not deserializing it. 但是这段代码并没有反序列化它。

I have also tried codes as below but none seems working 我也尝试过以下代码,但似乎都无法正常工作

  JavaScriptSerializer js = new JavaScriptSerializer();
  UnitDetail[] serializedData= js.Deserialize<UnitDetail[]>(json);

and also like below 而且也像下面

List<UnitDetail> serializedData= js.Deserialize<List<UnitDetail>>(json);

I am really not sure why it is not working. 我真的不确定为什么它不起作用。 Any help would really be appriciable. 任何帮助都将是切实可行的。

Thanks 谢谢

You need a root object 您需要一个根对象

public class UnitDetail
{
    public int Id { get; set; }
    public int UnitId { get; set; }
    public bool Active { get; set; }
    public string Name { get; set; }
    public string ContactNumber { get; set; }
}

public class RootObject
{
    [JsonProperty("odata.metadata")]
    public string odata_metadata { get; set; }
    public List<UnitDetail> value { get; set; }
}

Now you can deserialize as 现在您可以反序列化为

 var root = js.Deserialize<RootObject>(json);

尝试使用JsonHelper.Deserialize

List<UnitDetail> data = JsonHelper.Deserialize<List<UnitDetail>>(json);

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

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