C#反序列化JSON数据

时间:2017-04-28 14:54:56

标签: c# json serialization

我有一个JSON

{{  "action": "rma",  "devices": "[95001105,30013103,300117]",  "devandreason": [    {      "device": 95001105,      "reason": 100    },    {      "device": 30013103,      "reason": 300    },    {      "device": 300117,      "reason": 200    }  ]}}

我试图将devandreason作为数组。 我尝试过创建课程

public class DevReasonList
    {
        public List<DevReason> devandreason { get; set; }
    }
    public class DevReason
    {
        public Double device { get; set; }
        public Double reason { get; set; }
    }

json_serializer

JavaScriptSerializer json_serializer = new JavaScriptSerializer();
DevReasonList deviceAndReasonList = json_serializer.Deserialize<DevReasonList>(json.devandreason);

但它引发了一个例外:

  

json_serializer.Deserialize<DevReasonList>(json.devandreason) 'json_serializer.Deserialize<DevReasonList>(json.devandreason)' threw an exception of type 'Microsoft.CSharp.RuntimeBinder.RuntimeBinderException' dynamic {Microsoft.CSharp.RuntimeBinder.RuntimeBinderException}

但我不知道我做错了什么:(

可以反序列化devandreason并使其成为数组吗?

1 个答案:

答案 0 :(得分:5)

这应该是你的模型

public class Devandreason
{
    public int device { get; set; }
    public int reason { get; set; }
}

public class RootObject
{
    public string action { get; set; }
    public string devices { get; set; }
    public List<Devandreason> devandreason { get; set; }
}

我删除了开头{和尾随},现在验证了

{  "action": "rma",  "devices": "[95001105,30013103,300117]",  "devandreason": [    {      "device": 95001105,      "reason": 100    },    {      "device": 30013103,      "reason": 300    },    {      "device": 300117,      "reason": 200    }  ]}

奖金:http://json2csharp.com/

编辑: 由@Sven在评论中提出:如果您的设备类型是List,RootObject将更容易遍历。

这是需要的json,我只是删除了值之前的引号:

{  "action": "rma",  "devices": [95001105,30013103,300117],  "devandreason": [    {      "device": 95001105,      "reason": 100    },    {      "device": 30013103,      "reason": 300    },    {      "device": 300117,      "reason": 200    }  ]}