JSON Stand for JavaScript Object Notation. It is mostly used for transmitting the data in web applications. JSON is highly recommended to transfer data between a server and web application. To convert a Java object into JSON, the JACKSON API can be used:
In below example, Java object is converted into the JSON using the Jackson API:
Steps1: Add jar files of Jackson in the Maven project
Add Jackson dependencies in pom.xml file as below:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.5.3</version>
</dependency>
or Add below JARs manually to the Project's build path as external JARs:
jackson-core-asl-1.9.11.jar
jackson-mapper-asl-1.9.11.jar
jackson-xc-1.9.11.jar
Above are the Jackson API JARs which converts the Java Objects(POJO) to JSON and vice versa.
Steps2: Create a POJO (Plain Old Java Object) to be converted into JSON
The POJO class:
============
public class KeyValuePair {
public String key;
public String value;
// The getters and setters
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
Steps 3: Create a Java class for converting the JSON into KeyValuePair object. Below program converts the JSON into Java objects using ObjectMapper class of Jackson API.
import org.codehaus.jackson.map.ObjectMapper;
public class TestProgram {
public static void main(String[] args) {
String inputJson="{\"key\":\"Hello\", \"value\":\"World\"}";
ObjectMapper mapper = new ObjectMapper();
try {
KeyValuePair kv = mapper.readValue(inputJson, KeyValuePair.class);
System.out.println(kv.getKey());
System.out.println(kv.getValue());
} catch(Exception e) {
e.printStackTrace();
}
}
}
Output: (The Java Objects)
Hello
World
To convert the KeyValuePair POJO to JSON, we will use the following methods of Jackson API:
ObjectMapper Obj = new ObjectMapper();
try {
ObjectWriter ow = Obj.writer().withDefaultPrettyPrinter();
String jsonStr = ow.writeValueAsString(kv);
// Displaying JSON String
System.out.println(jsonStr);
}catch (IOException e) {
e.printStackTrace();
}
}
Output: (The JSON string)
{
"key": "Hello",
"value": "World"
}
Pankaj
Comments
Post a Comment