Json数组反序列化

时间:2015-07-27 23:15:39

标签: c# json json.net jsonserializer

如何在json数组下面反序列化。无法获取field_options值和field_options数组。我正在使用DataContractJsonSerializer进行反序列化。 我需要获取像size一样的field_options然后如果field_type是下拉列表我将需要field_options的值 - >选项 - > lebel和checked值以及include_blank_option。

string jsonString = @"[{""fields"":[{""label"":""Untitled"",""field_type"":""paragraph"",""required"":true,""field_options"":{""size"":""small""},""cid"":""c2""},{""label"":""Untitled"",""field_type"":""text"",""required"":true,""field_options"":{""size"":""small""},""cid"":""c6""},{""label"":""Untitled"",""field_type"":""dropdown"",""required"":true,""field_options"":{""options"":[{""label"":""kjhkjh"",""checked"":false},{""label"":"",hkjkhkj"",""checked"":false}],""include_blank_option"":true},""cid"":""c8""}]}]}";

    DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(List<field>));
    MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
    var obj = (List<field>)ser.ReadObject(stream);


        foreach (Person sp in obj[0].fields)
        {
            Response.Write(sp.cid + sp.field_type + sp.label + sp.required + "<BR>");
            List<sizee> si = sp.field_options;
            foreach (sizee sz in si)
            {
                Response.Write(sz.size);
            }
        }

[DataContract]
class field
{
    [DataMember]
    public List<Person> fields { get; set; }
}

[DataContract]
class Person
{
    [DataMember]
    public string label { get; set; }
    [DataMember]
    public string field_type { get; set; }
    [DataMember]
    public string required { get; set; }
    [DataMember]
    public string cid { get; set; }
    [DataMember]
    public List<sizee> field_options { get; set; }
}

[DataContract]
class sizee
{
    [DataMember]
    public string size { get; set; }
    [DataMember]
    public List<option> size { get; set; }
}

[DataContract]
class option
{
    [DataMember]
    public string checke { get; set; }
    [DataMember]
    public string label { get; set; }
}
提前多多感谢。

1 个答案:

答案 0 :(得分:0)

我经常发现将样本数据写入文件有助于解决这些类型问题。我公开了这些类,并在其中一个类中修复了一个重复的属性大小。

int spaces = s.length() - s.replaceAll("^\\s+", "").length();