如何反序列化JSON字符串?

时间:2013-08-20 19:39:41

标签: c# deserialization

我正在尝试为以下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; }
}

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

1 个答案:

答案 0 :(得分: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>树,您可以随意浏览。