简体   繁体   English

C#JSON反序列化字典 <string, Dictionary<string, string> &gt;可选?

[英]C# JSON Deserialize Dictionary<string, Dictionary<string, string>> optional?

My payload would look something like this: 我的有效负载如下所示:

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

My object simply has the following: 我的对象仅具有以下内容:

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

}

Obviously, this doesn't handle the LINES object. 显然,这不能处理LINES对象。 How can I create a class that deserializes an inbound payload where something like LINES is dynamic (ie I can send in any Dictionary> at any point in the payload and it'll deserialize correctly. Is this something when I need to create a custom JsonConverter? 我如何创建一个反序列化入站有效负载的类,其中类似LINES的内容是动态的(即,我可以在有效负载中的任何位置发送任何Dictionary>并将其正确反序列化。当我需要创建自定义JsonConverter时,是否需要这样做? ?

You could use dynamic instead. 您可以使用dynamic代替。

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

This should allow you to access (string)request.fields.lines.data directly in your code, for example. 例如,这应该允许您直接在代码中访问(string)request.fields.lines.data

However, if you don't know at compile time what values will be in there, you may prefer to make fields a JObject . 但是,如果您在编译时不知道其中会有什么值,则可以将字段设置为JObject

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

This gives you the opportunity to write code that inspects what kind of data is in each of its properties and respond accordingly. 这使您有机会编写代码来检查其每个属性中的数据类型并做出相应的响应。

Finally, if you do know what properties you expect fields to have, create a separate class for it. 最后,如果您确实知道期望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;}
}

Try changing 尝试改变

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

With

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM