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


3 comments:

keerthi said...

It's like you read my mind! You seem to know a lot about this, like you wrote the book in it or something. I think that you can do with some pics to drive the message home a little bit, but instead of that, this is fantastic blog. A great read. I will definitely be back.

Online Training in Chennai

Pranisha said...

Quick up your career with Azure Training in Chennai from Infycle Technologies, the best software training institute in Chennai. A massive place to learn topmost technical courses like Medical Coding, Mobile App Development, Data Science, Big Data, BlockChain, Full Stack Development, Digital Marketing with Graphic Design, Python, and Oracle with emphasized trainers of the industry. Speak to us on 7504633633, 7502633633 to know the updated offers for your learning.

Pranisha said...


Come up with a great learning experience of Azure training in Chennai, from Infycle Technologies, the best software training institute in Chennai. Get up with other technical courses like Data Science, Selenium Automation Testing, Mobile App Development, Cyber Security, Big Data, Full Stack Development with a great learning experience and outstanding placements in top IT firms. For best offers with learning, reach us on +91-7504633633, +91-7502633633.