无法反序列化JQuery插件

时间:2015-08-08 15:39:20

标签: javascript c# jquery json serialization

我使用JQuery插件让我的用户能够设计表单。设计以数据库中的JSON字符串形式保存。此JSON字符串采用以下格式:

{
    "fields": [{
        "label": "Untitled",
        "field_type": "text",
        "required": true,
        "field_options": {
            "save_to": "",
            "size": "small",
            "description": ""
        },
        "cid": "c5"
    }]
}

以下是C#类结构和用于反序列化此JSON字符串的代码:

public class Options {
    public string label {
        get;
        set;
    }
    public bool Checked {
        get;
        set;
    }
}
public class FieldOption {
    public string save_to {
        get;
        set;
    }
    public string description {
        get;
        set;
    }
    public object options {
        get;
        set;
    }
    public bool include_other_option {
        get;
        set;
    }
    public string size {
        get;
        set;
    }
}
public class DesignField {
    public string label {
        get;
        set;
    }
    public string field_type {
        get;
        set;
    }
    public bool required {
        get;
        set;
    }
    public string cid {
        get;
        set;
    }
    public List < FieldOption > field_options {
        get;
        set;
    }
}
public class Design {
    public List < DesignField > fields {
        get;
        set;
    }
}
public partial class FormDesign: System.Web.UI.UserControl {
    List < DesignField > FormFields;
    public string FormDesignData {
        get;
        set;
    }
    protected void Page_Load(object sender, EventArgs e) {
        Design res = JsonHelper.JsonDeserialize < Design > (FormDesignData);

         }
}

JSON Helper类在这里给出:http://www.codeproject.com/Articles/272335/JSON-Serialization-and-Deserialization-in-ASP-NET

问题是当内部JSON对象用[]括起来时它是反序列化的,例如:

"field_options":[{
            "save_to": "",
            "size": "small",
            "description": ""
        }]

但该插件不是以该格式导出JSON,而是以我之前提到的格式导出。

请告诉我如何将其转换为有效的反序列化格式?

1 个答案:

答案 0 :(得分:1)

根据你的json的模型应该是:

raw_json_file = open( script_dir + "raw_json.js", 'r', encoding='utf8' )

我使用此在线工具http://json2csharp.com/来生成它。

RootObject 是您将用于反序列化的类型

使用,例如Json.Net,您的代码将是

public class FieldOptions
{
    public string save_to { get; set; }
    public string size { get; set; }
    public string description { get; set; }
}

public class Field
{
    public string label { get; set; }
    public string field_type { get; set; }
    public bool required { get; set; }
    public FieldOptions field_options { get; set; }
    public string cid { get; set; }
}

public class RootObject
{
    public List<Field> fields { get; set; }
}