Amit Bhosale Amit Bhosale - 19 days ago 5
ASP.NET (C#) Question

Deserialize json object into SQL DB using Json.net

I want to deserialize json object into SQL DB using Json.net

Json File :

{
"requirements": {
"requirement": [
{
"Id": "req1",
"desc": "description of requirement1"
},
{
"Id": "req2",
"desc": "description of requirement2",
},
{
"desc": "description of requirement3",
"Id": "req3"
}
]
}
}


Such that values for 'Id' attribute should be places in ID column of Requirement table and values for 'desc' attribute should be places in DESC column of Requirement table

ID DESC
req1 description of requirement1
req2 description of requirement2
req3 description of requirement3

Answer
        string json = "{\"requirements\": {\"requirement\": [{\"Id\": \"req1\",\"desc\": \"description of requirement1\"},{\"Id\": \"req2\",\"desc\":\"description of requirement2\",},{\"desc\": \"description of requirement3\",\"Id\": \"req3\"}]}}";

        //Deserialize using Json.Net
        var objectRequirement = JsonConvert.DeserializeObject<RootObject>(json);

        //Add it to your database
        foreach (var item in objectRequirement.requirements.requirement)
        {
            db.Requirement.Add(new Requirement { ID = item.Id, DESC = item.desc });
        }
        db.SaveChanges();


U can use http://json2csharp.com/ to create your class:

    public class Requirement
    {
        public string Id { get; set; }
        public string desc { get; set; }
    }

    public class Requirements
    {
        public List<Requirement> requirement { get; set; }
    }

    public class RootObject
    {
        public Requirements requirements { get; set; }
    }