0

我正在尝试为以下具有动态列的 JSON 字符串创建模型,如下所示

[{"DId":0,"DData":[{"Date":"","C0":{"D":"National","Id":"National"},"C1":{"D":"National","Id":"National"},"C2":{"D":"National","Id":"National"}},{"Date":"1/2/2010","C0":{"D":0.74,"Id":1334337,"Dirty":"False"},"C1":{"D":0.6,"Id":1334597,"Dirty":"False"},"C2":{"D":1,"Id":1334857,"Dirty":"False"}}]}]

正如我突出显示的列 (C*) 它们是动态的,例如我可以有如下 JSON,其中我只有两列

[{"DId":0,"DData":[{"Date":"","C0":{"D":"National","Id":"National"},"C1":{"D":"National","Id":"National"}},{"Date":"1/2/2010","C0":{"D":0.74,"Id":1334337,"Dirty":"False"},"C1":{"D":0.6,"Id":1334597,"Dirty":"False"}}]}]

C0,C1,C2 .... 是动态的。

我正在尝试构建一个通用模型来反序列化我的 JSON 字符串。现在我的模型如下

public class C0
{
    public object D { get; set; }
    public object Id { get; set; }
    public string Dirty { get; set; }
}

public class C1
{
    public object D { get; set; }
    public object Id { get; set; }
    public string Dirty { get; set; }
}

public class C2
{
    public object D { get; set; }
    public object Id { get; set; }
    public string Dirty { get; set; }
}

public class DData
{
    public string Date { get; set; }
    public C0 C0 { get; set; }
    public C1 C1 { get; set; }
    public C2 C2 { get; set; }
}

public class Model
{
    public int DId { get; set; }
    public List<DData> DData { get; set; }
}

正如我上面提到的,分布数据可以有动态列。我真的很感激任何帮助。谢谢你。

4

1 回答 1

0

秘诀是让你的反序列化 JSON 尽可能采用最通用的形式:

Dictionary<string, object> theData= new JavaScriptSerializer().Deserialize<Dictionary<string, object>>(jsonString);

System.Collections.ArrayList dData= (System.Collections.ArrayList)theData["DData"];

foreach (Dictionary<string, object> data in dData)
{
 string date = (string)data["Date"];

 Dictionary<string, object> cZeroNode = (Dictionary<string, object>)data["C0"];

 string d = (string)cZeroNode["D"];
 string id = (string)cZeroNode["Id"];
}

调用Deserialize()创建一棵Dictionary<string, object>您可以随意遍历的树。

于 2015-06-24T20:04:47.197 回答