我有一个 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 } ]}
编辑: 正如 @Sven 在评论中提出的:如果您的设备类型是 List,则 RootObject 会更容易遍历。
这是所需的 json,我刚刚删除了值之前的引号:
{ "action": "rma", "devices": [95001105,30013103,300117], "devandreason": [ { "device": 95001105, "reason": 100 }, { "device": 30013103, "reason": 300 }, { "device": 300117, "reason": 200 } ]}
关于C# 反序列化 JSON 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43683175/