[Json] common operation records of fastjson and jackson

Posted by Jack_Slocum on Fri, 03 Jan 2020 05:10:22 +0100

This article only records some common operation methods of fastjson and jackson, but not for comparison. There are a lot of comparison articles written on the Internet.

1. Object to Json string

// fastjson                                                            
String objStr = JSON.toJSONString(obj);  // The default attribute to be removed is Null Valued

// jackson
ObjectMapper mapper = new ObjectMapper();
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); // Not removed by default Null You have to match it 
String objStr = mapper.writeValueAsString(obj);


2. Json string to Json object

// fastjson
JSONObject objJson = JSON.parseObject(objStr);

// jackson
ObjectMapper mapper = new ObjectMapper();
JsonNode objJson = mapper.readTree(objStr);


3. Json string to Java object

// fastjson
Clazz obj = JSON.parseObject(jsonStr, Clazz.class);

// jackson
ObjectMapper mapper = new ObjectMapper();
Clazz obj = mapper.readValue(jsonStr, Clazz.class);


4. Get the key of the Json object

// fastjson
Set<String> keySet = jsonObj.keySet();
String key = keySet.iterator().next();  // Get the first one key

// jackson
Iterator<String> keys = jsonObj.fieldNames();
String key = fieldNames.next();  // Get the first one key


5. Get the value of Json object

// fastjson

// jackson


6. Create a Json object and set key\value

// fastjson
JSONObject jsonObj = new JSONObject();
jsonObj.put("key", oldJsonObj);

// jackson
ObjectMapper mapper = new ObjectMapper();
ObjectNode jsonObj = mapper.createObjectNode();
jsonObj.set("key", oldJsonObj);

At this point, fastjson is directly handled by a JSONObject, while jsonode in jackson does not directly set the key/value method. Here, ObjectNode is used. jackson provides a tree model to generate and parse json. If you want to access and modify some properties, the tree model is a good choice. ObjectNode inherits from JsonNode. Here is an example:

ObjectMapper mapper = new ObjectMapper(); 
// Establish ObjectNode 
ObjectNode studentNode = mapper.createObjectNode(); 
// Add attribute 

ObjectNode addressNode = mapper.createObjectNode(); 

// Set child nodes 
// path Search node 
JsonNode searchNode = studentNode.path("street"); 
// Delete attribute 
((ObjectNode) studentNode).remove("addr"); 
// read
JsonNode rootNode = mapper.readTree(studentNode.toString()); 
// JsonNode turn java object 
Student student = mapper.treeToValue(studentNode, Student.class); 
// java Object turn JsonNode 
JsonNode node = mapper.valueToTree(student);

Topics: Java JSON Attribute