简体   繁体   English

我如何反序列化这种类型的数据结构

[英]How do I deserialize this type of data structure

This is my JSON: 这是我的JSON:

"Dt": {    
    "20171021": {    
      "abc": "-"    
    },    
    "20171022": {    
      "abc": "-"    
    },    
    "20171023": {    
      "abc": "-"    
    },    
    "20171024": {    
      "abc": "-"    
    },    
    "20171025": {    
      "abc": "-"    
    }
}

The properties inside Dt is all dynamic. Dt内部的属性都是动态的。 They are all dates but in string format. 它们都是日期,但为字符串格式。 So I am thinking if I would need a List object but how would JSON.Net map this into List? 所以我在考虑是否需要一个List对象,但是JSON.Net如何将其映射到List中? I am thinking of class structure something similar to: 我在想类结构类似于:

public class Dt
{
    public List<RealDate> RealDates { get; set;}
}

public class RealDate
{
    public string Date{ get; set;} //to hold "20171021"

    public Tuple<string, string> Keys {get; set;} // to hold abc as Key1 and - as Key2
}

Any help is appreciated. 任何帮助表示赞赏。

That look like there is no Dt , and the thing that currently has a Dt should actually have: 看起来好像没有Dt ,而当前具有 Dt的东西实际上应该具有:

public Dictionary<string, Foo> Dt { get; set;}

where Foo is: Foo在哪里:

class Foo {
    public string abc {get;set}
}

You would then post-process this to turn the DTO model (the serialization model) into your actual model. 然后,您将对此进行后处理,以将DTO模型(序列化模型)转换为实际模型。

Remember: any time that there is even a minor difference between what the serialized data looks like, and what your domain model looks like: add a DTO model, and just map between them manually. 请记住:只要序列化数据的外观与域模型的外观之间甚至存在细微的差别,就可以:添加DTO模型,然后手动在它们之间进行映射。 It'll save your sanity. 它将节省您的理智。

Your json is invalid (brackets are missing), but the following json 您的json无效(缺少括号),但是以下json

{
    "Dt": {
        "20171021": {
            "abc": "-"
        },
        "20171022": {
            "abc": "-"
        },
        "20171023": {
            "abc": "-"
        },
        "20171024": {
            "abc": "-"
        },
        "20171025": {
            "abc": "-"
        }
    }
}

Can be deserialized into the following objects: 可以反序列化为以下对象:

public class Model
{
    [JsonProperty("Dt")]
    public Dictionary<string, Value> Data { get; set; }
}

public class Value
{
    [JsonProperty("abc")]
    public string Abc { get; set; }
}

Testing the code: 测试代码:

string json = @"{
    ""Dt"": {    
    ""20171021"": {    
      ""abc"": ""-""    
    },    
    ""20171022"": {    
      ""abc"": ""-""    
    },    
    ""20171023"": {    
      ""abc"": ""-""    
    },    
    ""20171024"": {    
      ""abc"": ""-""    
    },    
    ""20171025"": {    
      ""abc"": ""-""    
    }
}
}";

var model = JsonConvert.DeserializeObject<Model>(json);

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

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