【问题标题】:C# JSON Deserialize Dictionary<string, Dictionary<string, string>> optional?C# JSON 反序列化 Dictionary<string, Dictionary<string, string>> 可选?
【发布时间】:2017-09-14 23:02:44
【问题描述】:

我的有效载荷看起来像这样:

{
    "REFERENCE": "1",
    "FIELDS" : {
        "CUST" : "1234",
        "PROD" : "PR2134",
        "LIMIT" : "12345",
        "LINES" : {
              "LINE" : "01",
              "DATA" : "12"
        }
    }
}

我的对象只有以下内容:

public class TriggerRequest
{
    public string reference { get; set; }
    public Dictionary<string, string> fields { get; set; }

}

显然,这不处理 LINES 对象。如何创建一个反序列化入站有效负载的类,其中 LINES 是动态的(即我可以在有效负载中的任何位置发送任何 Dictionary> 并且它会正确反序列化。这是我需要创建自定义 JsonConverter 时的东西吗? ?

【问题讨论】:

  • 这是因为它区分大小写..
  • 在开始使用自己的 JSON 转换器之前,您应该查看一些已经可用的包,包括 JSON.net 和 Silverlight 的 System.Json,其中大多数都能够反序列化为动态或 Dictionary&lt;string, object&gt;
  • 来自Newtonsoft.Json 库(AKA Json.net)的 JObject obj = JsonConvert.DeserializeJson(string json) 可能会很好地完成您想要完成的工作。

标签: c# json asp.net-web-api deserialization


【解决方案1】:

您可以改用dynamic

public class TriggerRequest
{
    public string reference { get; set; }
    public dynamic fields { get; set; }
}

例如,这应该允许您直接在代码中访问(string)request.fields.lines.data

但是,如果您在编译时不知道其中将包含哪些值,您可能更愿意将字段设为 JObject

public class TriggerRequest
{
    public string reference { get; set; }
    public JObject fields { get; set; }
}

这使您有机会编写代码来检查其每个属性中的数据类型并做出相应的响应。

最后,如果您确实知道您希望fields 具有哪些属性,请为它创建一个单独的类。

public class TriggerRequest
{
    public string reference { get; set; }
    public TriggerRequestFields fields { get; set; }
}

public class TriggerRequestFields
{
    public string cust {get;set;}
    ...
    public TriggerRequestLines lines {get;set;}
}

public class TriggerRequestLines
{
    public string line {get;set;}
    public string data {get;set;}
}

【讨论】:

    【解决方案2】:

    尝试改变

    public Dictionary<string, dynamic> fields { get; set; }
    

    public Dictionary<string, object> fields { get; set; }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-15
      • 1970-01-01
      相关资源
      最近更新 更多