Maven dependency -
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.6</version>
</dependency>
|
If you are beginner don't worry learn how to Create new Maven project - In 2 minutes
Convert JSON string to java Object - using Jackson Api
import java.io.IOException;
import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class ConvertJsonToJavaObject {
public static void main(String[] args) {
try {
ObjectMapper objectMapper = new ObjectMapper();
// Convert JSON string to java Object
String jsonInString = "{\"empId\":11,\"name\":\"Ankit\",\"address\":[\"Paris\",\"London\"]}";
System.out.println(jsonInString);
Employee emp = objectMapper.readValue(jsonInString, Employee.class);
//Note : do not forget to provide no-arg constructor in Employee class otherwise you will face
System.out.println(emp); //It will use toString method of Employee
} catch (JsonGenerationException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
//output
/*
jsonInString = {"empId":11,"name":"Ankit","address":["Paris","London"]}
Employee [empId=11, name=Ankit, address=[Paris, London]]
*/
|
Employee class
import java.util.List;
public class Employee {
//Fields
private int empId;
private String name;
private List<String> address;
public Employee() {
super();
}
public Employee(int empId, String name, List<String> address) {
super();
this.empId = empId;
this.name = name;
this.address = address;
}
@Override
public String toString() {
return "Employee [empId=" + empId + ", name=" + name + ", address=" + address + "]";
}
//Setter and getters
public int getEmpId() {
return empId;
}
public void setEmpId(int empId) {
this.empId = empId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<String> getAddress() {
return address;
}
public void setAddress(List<String> address) {
this.address = address;
}
}
|
TroubleShooting :
Note : do not forget to provide no-arg constructor in Employee class otherwise you will face
com.fasterxml.jackson.databind.JsonMappingException: No suitable constructor found for type [simple type, class com.mkyong.json.Employee]: can not instantiate from JSON object (missing default constructor or creator, or perhaps need to add/enable type information?)
at [Source: {"empId":11,"name":"Ankit","address":["Paris","London"]}; line: 1, column: 2]
Related links >
1. Jackson JSON -
We can use Jackson api for for processing JSON in java.
Jackson JSON examples
2. Java provides API (JSR 353) for Processing JSON (JSR 353).
It provides -
- Object Model API
- Streaming API
Java API for JSON processing examples >