fastjson recording operation and common jackson

Editor: 

fastjson recording operation and common jackson

 

This article is recorded fastjson, jackson some commonly used methods of operation, did not compare, compare online writing articles many friends.

1, the object-string Json

// fastjson                                                            
String objStr = JSON.toJSONString (obj); // remove the default attribute value to Null

// jackson
ObjectMapper mapper = new ObjectMapper();
mapper.setSerializationInclusion (JsonInclude.Include.NON_NULL); // default will not remove Null, to himself with
String objStr = mapper.writeValueAsString(obj);

 

2, Json Json string transfer objects

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

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

 

3, Json string transfer Java objects

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

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

 

4, get Json object key

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

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

 

5, get Json object's value

// fastjson
jsonObj.get("key")

// jackson
jsonObj.path("key")

 

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);

In this regard, a direct FASTJSON JSONObject buttoned, while the JsonNode jackson no direct method can set key / value, and to be used here ObjectNode, jackson provided tree model (tree model) to generate and parse json. If you want to access and modify some of the properties for the operation of tree model is a good choice, ObjectNode inherited from JsonNode, to the following example:

ObjectMapper mapper = new ObjectMapper(); 
// Create ObjectNode 
ObjectNode studentNode = mapper.createObjectNode(); 
// add properties 
studentNode.put("name","xiaoming"); 
studentNode.put("age",18); 

ObjectNode addressNode = mapper.createObjectNode(); 
addressNode.put("street","guangzhou"); 

// Set the child node 
studentNode.set("addr",addressNode); 
// path to find node 
JsonNode searchNode = studentNode.path("street"); 
// delete the property 
((ObjectNode) studentNode).remove("addr"); 
// Read
JsonNode rootNode = mapper.readTree(studentNode.toString()); 
// JsonNode turn java object 
Student student = mapper.treeToValue(studentNode, Student.class); 
// java objects go JsonNode 
JsonNode node = mapper.valueToTree(student);

Guess you like

Origin blog.csdn.net/hello_world123456789/article/details/88883659