Main components of Jackson are
- - Data Binding which contains the object mapper
- - Annotation and
- - Jackson core
In Jackson api there is no need for a separate mapping to serialize java objects to json
Jackson JSON Tree Model
Jackson has a built-in tree model which can be used to represent a JSON object. Jackson's tree model is useful if you don't know how the JSON you will receive looks, or if you for some reason cannot (or just don't want to) create a class to represent it.
Jackson process JSON in 3 different ways
Streaming API -
JSON Parser reads data and JSON Generator writes data
Tree Model -
Creates an in memory tree structure of the JSON document like DOM. Object mapper build tree of JSON nodes.
The Jackson tree model is represented by the JsonNode class. You use the Jackson ObjectMapper to parse JSON into a JsonNode tree model, just like you would have done with your own class.
Object mapper builds the tree and tree consists of JSON Nodes
Data Binding -
- It converts JSON to and from Plain Old Java Object (POJO) using property accessor or using annotations. ObjectMapper reads/writes JSON for both types of data bindings. Data binding is analogous to JAXB parser for XML. Data binding is of two types −
- Simple Data Binding − It converts JSON to and from Java Maps, Lists, Strings, Numbers, Booleans, and null objects.
- Full Data Binding − It converts JSON to and from any Java type.
Example of JSON PARSER using Streaming API
public static void jacksonJSONparser() {
String fruitJSON = "{ \"name\" : \"apple\", \"quantity"\" : 5 }";
JsonFactory jfactory = new JsonFactory();
try {
JsonParser parser = jfactory.createParser(fruitJSON);
while (!parser.isClosed()) {
JsonToken token = parser.nextToken();
// System.out.println(token);
if (JsonToken.FIELD_NAME.equals(token)) {
String fieldName = parser.getCurrentName();
System.out.println(fieldName);
parser.nextToken();
if (fieldName.equals("brand")) {
System.out.println(parser.getValueAsString());
}
if (fieldName.equals("doors")) {
System.out.println(parser.getValueAsInt());
}
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
OR to get all the Name an Value simple use
if (fieldName.equals(fieldName)) {
System.out.println(parser.getValueAsString());
}
A more complex JSON read using Jackson streaming API
Code To read the JSON
public static void jacksonJSONparser() {
String carJson = "{ \"brand\" : \"Mercedes\", \"doors\" : 5 }";
JsonFactory jfactory = new JsonFactory();
try {
JsonParser parser = jfactory.createParser(new File("/Users/S_Das/Documents/Java/sudas.com.au/user.json"));
while (!parser.isClosed()) {
JsonToken token = parser.nextToken();
// System.out.println(token);
if (JsonToken.FIELD_NAME.equals(token)) {
String fieldName = parser.getCurrentName();
System.out.println("name: "+fieldName);
parser.nextToken();
if (fieldName.equals(fieldName) && parser.getValueAsString() !=null) {
System.out.println("value: "+parser.getValueAsString());
}
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Output:
Using Jackson Data Binding converting a POJO to JSON
My POJO class
package com.rest.client;
import java.util.List;
public class UserModel {
String firstName;
String lastName;
String address;
int age;
List<String> hobbies;
public UserModel() {
// TODO Auto-generated constructor stub
}
public UserModel(String firstName, String lastName, String address, int age, List<String> hobbies) {
super();
this.firstName = firstName;
this.lastName = lastName;
this.address = address;
this.age = age;
this.hobbies = hobbies;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public List<String> getHobbies() {
return hobbies;
}
public void setHobbies(List<String> hobbies) {
this.hobbies = hobbies;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
Code to convert POJO to JSON and write to a file
package com.rest.client;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JacksonDataBinding {
public static void main(String[] args) {
createJSON();
}
public static void createJSON() {
List<String> hobbies = new ArrayList<>();
List<String> lists = Arrays.asList("Java Coding", "Car Driving", "DIY");
hobbies.addAll(lists);
UserModel userOne = new UserModel("subhra", "das", "India", 35, hobbies);
ObjectMapper mapper = new ObjectMapper();
try {
// convert user object to json and writes to file
mapper.writeValue(new File("/Users/S_Das/Documents/Java/sudas.com.au/Newuser.json"), userOne);
// convert user object to json and prints in pretty format
System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(userOne));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Update Name Value in JSON
public static void modifyJSON()
{
ObjectMapper mapper = new ObjectMapper();
try {
JsonNode tree = mapper.readTree(new File("/Users/S_Das/Documents/Java/sudas.com.au/Newuser.json"));
String printPretty = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(tree);
System.out.println(printPretty);
// Changing field name value in json
((ObjectNode)tree).put("firstName", "Sharanya");
String printPretty1 = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(tree);
System.out.println(printPretty1);
//writing the changed value to file
mapper.writeValue(new File("/Users/S_Das/Documents/Java/sudas.com.au/Newuser.json"), tree);
System.out.println(tree.path("lastName").asText());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Hello World
No comments:
Post a Comment