gpt4 book ai didi

C# 反序列化 JSON 数据

转载 作者:行者123 更新时间:2023-12-02 21:01:59 25 4
gpt4 key购买 nike

我有一个 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    }  ]}

关于C# 反序列化 JSON 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43683175/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com