JSON for Beginners – 101

In last couple of months few of my colleagues and friends asked me what is JSON? Why do we use it etc. I thought it will be good idea if I make a tutorial video and share it with the world.

This article covers the highlights of the video tutorial and sample examples I have demonstrated.

If you are new to the world of Web application or mobile application common problem you face is dealing with JSON. Now everyone build their application is REST API and JSON is the data format used for it.

First question to answer is “What is JSON”? Well, its JavaScript Object Notation. Its an data structure initially built in JavaScript and later used would wide due to its simplicity.

JSON has very less Objects and properties. Here is the list you must know before you looking at a sample json structure.

Here is a sample JSON for a person object.

{
    "firstName": "John",
    "lastName": "Smith",
    "age": 25,
    "address": {
        "streetAddress": "21 2nd Street",
        "city": "New York",
        "state": "NY",
        "postalCode": "10021"
    },
    "phoneNumber": [
        {
            "type": "home",
            "number": "212 555-1234"
        },
        {
            "type": "fax",
            "number": "646 555-4567"
        }
    ],
    "gender": {
        "type": "male"
    }
}

To map this object into Java, we need to first identify what are the objects associated with the JSON.

  • Person
    • First Name
    • Last Name
    • Age
    • Address
    • Phone Number – List
    • Gender
  • Address
    • Street Address
    • City
    • State
    • Postal code
  • Phone Number
    • Type
    • Number
  • Gender
    • Type

For such structure we need 4 classes Person, Address, PhoneNumber and Gender.

/**
 *
 */
package edu.vjleaning.jsondemo.pojo;

import java.util.List;

/**
 * @author vjlearning
 *
 */
public class Person {

	private String firstName;
	private String lastName;
	private int age;
	private Address address;
	private List<PhoneNumber> phoneNumbers;
	private Gender gender;
	/**
	 * @return the firstName
	 */
	public String getFirstName() {
		return firstName;
	}
	/**
	 * @param firstName the firstName to set
	 */
	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}
	/**
	 * @return the lastName
	 */
	public String getLastName() {
		return lastName;
	}
	/**
	 * @param lastName the lastName to set
	 */
	public void setLastName(String lastName) {
		this.lastName = lastName;
	}
	/**
	 * @return the age
	 */
	public int getAge() {
		return age;
	}
	/**
	 * @param age the age to set
	 */
	public void setAge(int age) {
		this.age = age;
	}
	/**
	 * @return the address
	 */
	public Address getAddress() {
		return address;
	}
	/**
	 * @param address the address to set
	 */
	public void setAddress(Address address) {
		this.address = address;
	}
	/**
	 * @return the phoneNumbers
	 */
	public List<PhoneNumber> getPhoneNumbers() {
		return phoneNumbers;
	}
	/**
	 * @param phoneNumbers the phoneNumbers to set
	 */
	public void setPhoneNumbers(List<PhoneNumber> phoneNumbers) {
		this.phoneNumbers = phoneNumbers;
	}
	/**
	 * @return the gender
	 */
	public Gender getGender() {
		return gender;
	}
	/**
	 * @param gender the gender to set
	 */
	public void setGender(Gender gender) {
		this.gender = gender;
	}

}
/**
 *
 */
package edu.vjleaning.jsondemo.pojo;

/**
 * @author vjlearning
 *
 */
public class Address {

	private String streetAddress;
	private String city;
	private String state;
	private String postalCode;
	/**
	 * @return the streetAddress
	 */
	public String getStreetAddress() {
		return streetAddress;
	}
	/**
	 * @param streetAddress the streetAddress to set
	 */
	public void setStreetAddress(String streetAddress) {
		this.streetAddress = streetAddress;
	}
	/**
	 * @return the city
	 */
	public String getCity() {
		return city;
	}
	/**
	 * @param city the city to set
	 */
	public void setCity(String city) {
		this.city = city;
	}
	/**
	 * @return the state
	 */
	public String getState() {
		return state;
	}
	/**
	 * @param state the state to set
	 */
	public void setState(String state) {
		this.state = state;
	}
	/**
	 * @return the postalCode
	 */
	public String getPostalCode() {
		return postalCode;
	}
	/**
	 * @param postalCode the postalCode to set
	 */
	public void setPostalCode(String postalCode) {
		this.postalCode = postalCode;
	}

}

/**
 *
 */
package edu.vjleaning.jsondemo.pojo;

/**
 * @author vjlearning
 *
 */
public class PhoneNumber {

	private String type;
	private String number;
	/**
	 * @return the type
	 */
	public String getType() {
		return type;
	}
	/**
	 * @param type the type to set
	 */
	public void setType(String type) {
		this.type = type;
	}
	/**
	 * @return the number
	 */
	public String getNumber() {
		return number;
	}
	/**
	 * @param number the number to set
	 */
	public void setNumber(String number) {
		this.number = number;
	}

}


package edu.vjleaning.jsondemo.pojo;

/**
 * @author vjlearning
 *
 */
public class Gender {

	private String type;

	/**
	 * @return the type
	 */
	public String getType() {
		return type;
	}

	/**
	 * @param type the type to set
	 */
	public void setType(String type) {
		this.type = type;
	}

}

We can directly map the JOSN structure into POJO project we have created. Jackson helps us to do that.

If you use a maven project here is the dependency you need to add to your pom.xml

<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core -->
<dependency>
	<groupId>com.fasterxml.jackson.core</groupId>
	<artifactId>jackson-core</artifactId>
	<version>2.8.8</version>
</dependency>

Finally lets create a JsonDemoImpl class which reads person.json file and convert into person object. Similarly we will use the person object to get our json string back.

/**
 *
 */
package edu.vjleaning.jsondemo.main;

import java.io.File;
import java.io.IOException;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.ObjectMapper;

import edu.vjleaning.jsondemo.pojo.Person;

/**
 * @author vjlearning
 *
 */
public class JSONDemoImpl {

	/**
	 * @param args
	 */
	public static void main(String[] args) {

		File inputJsonFile = new File("person.json");

		try {
			//Convert JSON string into person Object
			Person person = new ObjectMapper().readValue(inputJsonFile, Person.class);

			System.out.println(person);

			//Convert person object into json String
			String jsonString = new ObjectMapper().writeValueAsString(person);

			System.out.println(jsonString);

		}
		catch(JsonParseException e){
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

}

 

Codebase :

https://github.com/vjlearning/JSONLearning

Thanks for visiting my blog. If you have any questions or suggestions, feel free drop a comment. You can also drop an email to info.vjlearning@gmail.com

Learn . Practice . Improve

Happy Learning.

Leave a comment

Create a website or blog at WordPress.com

Up ↑