StellaMaris
StellaMaris

Reputation: 867

JSON model binding with variable keys .net mvc4

What is a useful model which could bind a json object with arbitrary keys? Assume your json could look like:

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

or

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

or

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

So that means you only know at run time how the json model looks like. My current state is, that it seems the best practice is to send the json object as string to the controller and deserialize the json string it to an object.

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

Upvotes: 0

Views: 375

Answers (1)

Emiliano Barboza
Emiliano Barboza

Reputation: 485

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);

Upvotes: 1

Related Questions