What is JSON and How to iterate through the JSON object?

JSON stands for JavaScript Object Notation. JSON is a lightweight format for storing and transporting data. JSON is often used when data is sent from a server to a web page.

Iterating through a JSON object can be done by.

Jackson API

Jackson JSON Java Parser is very popular and used in parsing JSON objects to Java Objects. Java JSON Processing API is not very user-friendly and doesn’t provide features for automatic transformation from Json to Java object and vice versa.

Jackson API can be implemented using an Object Mapper function.

Below given is an example of using Jackson API to convert JSON to JAVA object.

Note: For the given task, you do not have to declare a POJO , a POJO class called PortfolioTrade.java is provided for the same , where the values from Trades.json have to be read.

Given a JSON object:

        {
      "id": 123,
      "name": "Pankaj",
      "permanent": true,
      "role": "Manager",
}

The respective POJO for this JSON is given by:

public class Employee {

	private int id;
	private String name;
	private boolean permanent;
	private String role;
	
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public boolean isPermanent() {
		return permanent;
	}
	public void setPermanent(boolean permanent) {
		this.permanent = permanent;
	}
		public String getRole() {
		return role;
	}
	public void setRole(String role) {
		this.role = role;
	}
	}

Now to connect the JSON object to the JAVA object, we make use of an Object Mapper function.

ObjectMapper objectMapper = new ObjectMapper();
Employee emp = objectMapper.readValue(jsonData, Employee.class);

There is a method getObjectMapper already declared for you in PortfolioManagerApplication.java, this returns the instance of ObjectMapper class.

You can read more about different methods within Object Mapper in the given below link.

In the case of multiple objects in JSON, please refer to the following FAQ,

1 Like