user3521992
user3521992

Reputation: 23

Binding JSON to Model C#

I have a HttpPost request to my Web API and save the data to my database. The problem is the JSON data is not in a static format, like this:

{
"35":{
"FormId":"4",
"DateSubmitted":"2014-04-03 10:45:05",
"UserIp":"127.0.0.1",
"Username":"",
"UserId":"0",
"Lang":"en-GB",
"confirmed":"Yes"
},
"36":{
"FormId":"4",
"DateSubmitted":"2014-04-04 02:18:52",
"UserIp":"127.0.0.1",
"Username":"",
"UserId":"0",
"Lang":"en-GB",
"confirmed":"Yes"
}
}

35 and 36 here can be any number and I don't know how to bind this to a Model. Anyone can show me a way :(? Thanks in Advance

Upvotes: 1

Views: 7525

Answers (1)

kmacdonald
kmacdonald

Reputation: 3481

here is a quick example of how to achieve what i think you are going for using JSON.Net and the dynamic keyword. I stripped out some properties for simplicity sake:

[HttpPost]
public void POST(string text)
{
    dynamic result = JsonConvert.DeserializeObject(text);
    foreach (var res in result)
    {
        var ele = new Test();
        ele.ArrayId = int.Parse(res.Name);
        dynamic value = res.Value;
        ele.FormId = int.Parse(value.FormId.Value);
        ele.Ip = value.UserIp.Value;
        //etc.
    }
}

and the model class to go along with it:

public class Test
{
    public int ArrayId { get; set; }
    public int FormId { get; set; }
    public string Ip { get; set; }
}

Upvotes: 2

Related Questions