Tutorial on using Jackson to transform Java objects to and from JSON
- 2020-04-01 04:36:14
- OfStack
Introduction to a,
There is an ObjectMapper class in Jackson that is useful for interchangeability between Java objects and JSON.
1.JAVA object to JSON[JSON serialization]
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JacksonDemo {
public static void main(String[] args) throws ParseException, IOException {
User user = new User();
user.setName(" wang ");
user.setEmail("xiaomin@sina.com");
user.setAge(20);
SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd");
user.setBirthday(dateformat.parse("1996-10-01"));
ObjectMapper mapper = new ObjectMapper();
//The User class turn JSON
//Output result: {"name":" xiaomin ","age":20,"birthday":844099200000,"email":"xiaomin@sina.com"}
String json = mapper.writeValueAsString(user);
System.out.println(json);
//Java collection to JSON
//Output: [{" name ":" wang ", "age" : 20, "birthday" : 844099200000, "email" : "xiaomin@sina.com"}]
List<User> users = new ArrayList<User>();
users.add(user);
String jsonlist = mapper.writeValueAsString(users);
System.out.println(jsonlist);
}
}
2.JSON to Java class [JSON deserialization]
import java.io.IOException;
import java.text.ParseException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JacksonDemo {
public static void main(String[] args) throws ParseException, IOException {
String json = "{"name":" wang ","age":20,"birthday":844099200000,"email":"xiaomin@sina.com"}";
ObjectMapper mapper = new ObjectMapper();
User user = mapper.readValue(json, User.class);
System.out.println(user);
}
}
Ii. Jackson supports three modes of use:
1. Data Binding: most convenient to use.
(1) Full Data Binding:
private static final String MODEL_BINDING = "{"name":"name1","type":1}";
public void fullDataBinding() throws Exception{
ObjectMapper mapper = new ObjectMapper();
Model user = mapper.readValue(MODEL_BINDING, Model.class);//ReadValue into an entity class.
System.out.println(user.getName());
System.out.println(user.getType());
}
Model class:
private static class Model{
private String name;
private int type;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
}
(2) the Raw Data Binding:
public void rawDataBinding() throws Exception{
ObjectMapper mapper = new ObjectMapper();
HashMap map = mapper.readValue(MODEL_BINDING,HashMap.class);//ReadValue to a raw data type.
System.out.println(map.get("name"));
System.out.println(map.get("type"));
}
(3) the generic Data Binding:
private static final String GENERIC_BINDING = "{"key1":{"name":"name2","type":2},"key2":{"name":"name3","type":3}}";
public void genericDataBinding() throws Exception{
ObjectMapper mapper = new ObjectMapper();
HashMap<String,Model> modelMap = mapper.readValue(GENERIC_BINDING,new TypeReference<HashMap<String,Model>>(){});//ReadValue to a schema data.
Model model = modelMap.get("key2");
System.out.println(model.getName());
System.out.println(model.getType());
}
2. Tree Model: the most flexible.
private static final String TREE_MODEL_BINDING = "{"treekey1":"treevalue1","treekey2":"treevalue2","children":[{"childkey1":"childkey1"}]}";
public void treeModelBinding() throws Exception{
ObjectMapper mapper = new ObjectMapper();
JsonNode rootNode = mapper.readTree(TREE_MODEL_BINDING);
//Path does the same thing as get, but returns missing node instead of Null when the node is not found.
String treekey2value = rootNode.path("treekey2").getTextValue();//
System.out.println("treekey2value:" + treekey2value);
JsonNode childrenNode = rootNode.path("children");
String childkey1Value = childrenNode.get(0).path("childkey1").getTextValue();
System.out.println("childkey1Value:"+childkey1Value);
//Create a root node
ObjectNode root = mapper.createObjectNode();
//Create child node 1
ObjectNode node1 = mapper.createObjectNode();
node1.put("nodekey1",1);
node1.put("nodekey2",2);
//Bind child node 1
root.put("child",node1);
//An array of node
ArrayNode arrayNode = mapper.createArrayNode();
arrayNode.add(node1);
arrayNode.add(1);
// The binding An array of node
root.put("arraynode", arrayNode);
//JSON reads to the tree node
JsonNode valueToTreeNode = mapper.valueToTree(TREE_MODEL_BINDING);
//Bind JSON node
root.put("valuetotreenode",valueToTreeNode);
//JSON is bound to the JSON node object
JsonNode bindJsonNode = mapper.readValue(GENERIC_BINDING, JsonNode.class);//Bind JSON to the JSON node object.
//Bind JSON node
root.put("bindJsonNode",bindJsonNode);
System.out.println(mapper.writeValueAsString(root));
}
3. Streaming API: best performance.
For high performance programs, it is recommended to use the stream API, otherwise use other methods
JsonFactory is used to create either a JsonGenerator or a JsonParser.
package com.jingshou.jackson;
import java.io.File;
import java.io.IOException;
import com.fasterxml.jackson.core.JsonEncoding;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
public class JacksonTest6 {
public static void main(String[] args) throws IOException {
JsonFactory jfactory = new JsonFactory();
JsonGenerator jGenerator = jfactory.createGenerator(new File(
"c:\user.json"), JsonEncoding.UTF8);
jGenerator.writeStartObject(); // {
jGenerator.writeStringField("name", "mkyong"); // "name" : "mkyong"
jGenerator.writeNumberField("age", 29); // "age" : 29
jGenerator.writeFieldName("messages"); // "messages" :
jGenerator.writeStartArray(); // [
jGenerator.writeString("msg 1"); // "msg 1"
jGenerator.writeString("msg 2"); // "msg 2"
jGenerator.writeString("msg 3"); // "msg 3"
jGenerator.writeEndArray(); // ]
jGenerator.writeEndObject(); // }
jGenerator.close();
JsonParser jParser = jfactory.createParser(new File("c:\user.json"));
// loop until token equal to "}"
while (jParser.nextToken() != JsonToken.END_OBJECT) {
String fieldname = jParser.getCurrentName();
if ("name".equals(fieldname)) {
// current token is "name",
// move to next, which is "name"'s value
jParser.nextToken();
System.out.println(jParser.getText()); // display mkyong
}
if ("age".equals(fieldname)) {
// current token is "age",
// move to next, which is "name"'s value
jParser.nextToken();
System.out.println(jParser.getIntValue()); // display 29
}
if ("messages".equals(fieldname)) {
jParser.nextToken(); // current token is "[", move next
// messages is array, loop until token equal to "]"
while (jParser.nextToken() != JsonToken.END_ARRAY) {
// display msg1, msg2, msg3
System.out.println(jParser.getText());
}
}
}
jParser.close();
}
}