我有一个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并将其设置为数组吗?

最佳答案

根据您的模型,这应该是

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    }  ]}

10-06 12:19