JSON模型绑定与变量键.net mvc4

时间:2016-08-05 14:15:32

标签: c# asp.net-mvc-4

什么是可以用任意键绑定json对象的有用模型?假设你的json看起来像:

{"@@hello": "address","#world": "address1","name": "address"}

{"@@hello": "address","#world": "address1","firstname": "foo", "lastname":"bar"}

{"@@hello": "address","#world": "address1","children": [{"name":"foo"},{"name":"bar"}]}

这意味着你只能在运行时知道json模型的样子。我目前的状态是,似乎最好的做法是将json对象作为字符串发送到控制器,并将json字符串反序列化为对象。

  public ActionResult mappingNodes(string model) {
            dynamic json = Newtonsoft.Json.JsonConvert.DeserializeObject(model);
}

1 个答案:

答案 0 :(得分:1)

public class Children
    {
        [JsonProperty("name")]
        public string Name { get; set; }
    }
    public class YourClass
    {
        [JsonProperty("@@hello")]
        public string Hello { get; set; }
        [JsonProperty("#world")]
        public string World { get; set; }
        [JsonProperty("name")]
        public string Name { get; set; }
        [JsonProperty("firstname")]
        public string FirstName { get; set; }
        [JsonProperty("lastname")]
        public string LastName { get; set; }
        [JsonProperty("children")]
        public Children[] Children { get; set; }
    }



        var json1 = "{ '@@hello': 'address','#world': 'address1','name': 'address'}";
        var json2 = "{ '@@hello': 'address','#world': 'address1','name': 'address', 'firstname': 'foo', 'lastname':'bar'}";
        var json3 = "{ '@@hello': 'address','#world': 'address1','name': 'address','children': [{'name':'foo'},{'name':'bar'}]}";


        var model1 = JsonConvert.DeserializeObject<YourClass>(json1);
        var model2 = JsonConvert.DeserializeObject<YourClass>(json2);
        var model3 = JsonConvert.DeserializeObject<YourClass>(json3);