如何反序列化此类数据结构

问题描述 投票:1回答:2

这是我的JSON:

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

Dt内的属性都是动态的。它们都是日期,但是以字符串格式。所以我在想如果我需要一个List对象,但是JSON.Net如何将它映射到List?我在想类结构类似于:

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
}

任何帮助表示赞赏。

c# .net json json.net
2个回答
5
投票

看起来没有Dt,而且目前有Dt的东西应该具有:

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

其中Foo是:

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

然后,您将对此进行后处理,以将DTO模型(序列化模型)转换为实际模型。

请记住:任何时候序列化数据看起来与您的域模型之间存在细微差别:添加DTO模型,只需手动映射它们。它会拯救你的理智。


1
投票

你的json无效(括号丢失),但是下面是json

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

可以反序列化为以下对象:

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

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

测试代码:

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

var model = JsonConvert.DeserializeObject<Model>(json);
© www.soinside.com 2019 - 2024. All rights reserved.