c# - 处理每次都不相同的 JSON 响应

标签 c# json exception

我正在使用 json.net 反序列化 json -> C# 对象。

它在大多数情况下都很好用,但有时我得到的不是数组而是对象。

所以我的类(使用 http://json2csharp.com/ 生成并修改以添加属性)。 如果我有超过 1 种到达方式(例如自提或运送),它工作正常。

public class ArrivalMethods
    {
        [JsonProperty(PropertyName = "ArrivalMethod")]
        public List<string> ArrivalMethod { get; set; }
    }

但它在我的服务的 json 响应中只有 1 个到达方法的地方中断了,因为我相信 json.net 期待一个如下所示的对象。

public class ArrivalMethods
    {
        [JsonProperty(PropertyName = "ArrivalMethod")]
        public string ArrivalMethod { get; set; }
    }

我是 json 等方面的新手,所以我不确定自己做错了什么。但这会引发异常。

    Error converting value \"Ship\" to type 'System.Collections.Generic.List`1[System.String]'. 
Path 'ProductDetail.SoftHardProductDetails.Fulfillment.
ArrivalMethods.ArrivalMethod', line 1, position 113."

这里是中断的地方:

"ArrivalMethods":{
"ArrivalMethod":"Ship"
},

最佳答案

您的 JSON 应在有列表的地方包含 []。如果我理解你的答案是正确的,一流的例子就是你想要结束的方式?如果是这样,您需要底部的 JSON 将 ArrivalMethod 标记为列表,但现在不是。

"ArrivalMethods":
{
"ArrivalMethod":["Ship"]
},

老实说,当列表没有复数结尾时,我会有点困惑。

关于c# - 处理每次都不相同的 JSON 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20484000/

相关文章:

android - java.lang.IllegalArgumentException : View not attached to window manager 异常

java.lang.NullPointerException 找不到源

javascript - 如何使用来自 rest api json 的 jQuery Datatable 插件?

Android - 如何使用 SQLite 缓存 Json

Java:获取枚举的 ExceptionInInitializerError

c# - Azure 服务启动日志

c# - MS Access 数据库更新不更新使用 c#

c# - 如何在用户关闭浏览器时通知网络服务器(在 asp.net 中)?

c# - 如何通过使用 MVVM 的 Prism (+ MEF) View 中的特定控件的可用性来控制 WPF 4.5 Ribbons 上下文选项卡的可见性?

ios - 使用 Alamofire 验证 JSON 响应