Saturday, September 2, 2017

How to convert JSON String to POJO using Object Mapper

The present world of programming includes REST calls a lot,thus increasing the deals with JSON format.



JSON object is the standard format for JavaScript,So while using it with other languages you have to  parse JSON to your requirement.

In this post we will see how to do it in favour of Java.

In this example,

  1. At first we will construct a JSON string.
  2. Create a POJO class to map JSON.
  3. Creates Object Mapper instance.
  4. Convert JSON string to POJO.
So we will have two .java files. One for POJO class and other one is main class.

Main class - SamplePOJO.java


package stringtopojo;

import com.fasterxml.jackson.databind.ObjectMapper;

public class SamplePOJO {

public static void main(String[] args) {

try {

String address = "{" + "\"name\"" + ":" + "\"Jake\"" + ',' + "\"house\""
+ ":" + "\"Los Angels\"" + "}";
System.out.println("JSON String - "+address);

ObjectMapper mapper = new ObjectMapper();

ConvertJSONToPOJO jsonToPOJO = new ConvertJSONToPOJO();

jsonToPOJO = (ConvertJSONToPOJO) mapper.readValue(address,
ConvertJSONToPOJO.class);
System.out.println("POJO Object Name - "+jsonToPOJO.getName());
System.out.println("POJO Object House - "+jsonToPOJO.getHouse());

} catch (Exception e) {
System.out.println("Execption - "+e.getMessage());
}

}

}

POJO class - ConvertJSONToPOJO.java

package stringtopojo;

public class ConvertJSONToPOJO {
String name;
String house;
public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getHouse() {
return house;
}

public void setHouse(String house) {
this.house = house;
}

}

The console be like,

JSON String - {"name":"Jake","house":"Los Angels"}
POJO Object Name - Jake
POJO Object House - Los Angels

For complex JSON, you have to make POJO class in similar way.
If you are having some trouble post the JSON in comment,we will  try to parse it.

Thanks.


More Related Posts @Tech

No comments:

Post a Comment