serving the solutions day and night

Pages

Friday, April 1, 2016

Convert JSON to Object using Json.NET

sample json file
[{"empNumber":"123456","primaryName":{"firstName":"FN","lastName":"LN"},"disability":false,"otherNames":[{"firstName":"FN","lastName":"LN1"},{"firstName":"FN","lastName":"LN2"}],"homeAddress":{"addressLine1":"1234 Python Java Rd","city":"Bellevue","state":"WI","postalCode":"628204"}},{"empNumber":"7890","primaryName":{"firstName":"1FN","lastName":"1LN"},"disability":true,"otherNames":[{"firstName":"1FN","lastName":"1LN1"},{"firstName":"1FN","lastName":"1LN2"}],"homeAddress":{"addressLine1":"5869 Dotnet CRM St","city":"Chicago","state":"NE","postalCode":"567567"}}]

Download Json.NET dll from http://www.newtonsoft.com/json


Class Objects
public class Names
{
public string firstName { get; set; }
public string lastName { get; set; }
}

public class Address
{
public string addressLine1 { get; set; }
public string city { get; set; }
public string state { get; set; }
public string postalCode { get; set; }
}

public class Employee
{
public string empNumber { get; set; }
public Names primaryName { get; set; }
public bool disability { get; set; }
public IList<Names> otherNames { get; set; }
}

Read the JSON file 
string jsondatas = File.ReadAllText(JSONFile);

Convert json datas to Employee object array
Employee[] emps = JsonConvert.DeserializeObject<Employee[]>(jsondatas);

for loop to get each object.
foreach (Employee emp in emps)
{
    //convert object back to json string
    string jsonemp = Newtonsoft.Json.JsonConvert.SerializeObject(emp);
   
    //convert json to object
    Employee emp1 = JsonConvert.DeserializeObject<Employee>(jsonemp);
}


No comments: