Summary
Jackson framework is a set of data processing tools based on Java platform, which is called "the best Java Json parser".
The Jackson framework contains three core libraries: streaming, databind and annotations. Jackson also contains other data processing class libraries, which are not explained.
Jackson version: 1.x (current version 1.1-1.9) and 2.x. 1. X and 2. x can be seen from the naming of packages. In the class library of 1. x, the package name begins with: org. codehaus. jackson. x xxx, while in the class library of 2. x, the command begins with: com. fastxml. jackson. xxxx.
Jackson Home Page: https://github.com/FasterXML/jackson
Jackson Wiki: http://wiki.fasterxml.com/JacksonHome
Jackson doc: https://github.com/FasterXML/jackson-docs
Jackson Download Page: http://wiki.fasterxml.com/JacksonDownload
Dead work
All the programs in this paper are based on JDK 1.7 and depend on three core class libraries of jackon:
jackson-core-2.5.3.jar
jackson-annotations-2.5.3.jar
jackson-databind-2.5.3.jar
Jackson handles Json
Jackson provides three alternative Json processing methods: Streaming API, Tree Model, and Data Binding. From a usage point of view, compare the characteristics of these three ways of dealing with Json:
Streaming API: The most efficient way to process (low overhead, fast read and write, but high programming complexity)
Tree Model: The most flexible approach
Data Binding: The most commonly used method of processing
Next, we create and parse Json strings by using DataBinding, TreeModel and Streaming, respectively.
1. Data Binding handles Json
Jackson supports the transformation between Java objects and Json. Java objects can be serialized into JSON strings, and JSON strings can also be deserialized into the same Java objects.
(1)java objects are converted to json:
Province.java
-
package com.jackson.json.databinding;
-
-
public class Province {
-
public String name;
-
public int population;
-
public String[] city;
-
}
Country.java
-
package com.jackson.json.databinding;
-
-
import java.util.ArrayList;
-
import java.util.Arrays;
-
import java.util.Date;
-
import java.util.HashMap;
-
import java.util.List;
-
import java.util.Map;
-
-
public class Country {
-
-
private String country_id;
-
private Date birthDate;
-
private List<String> nation = new ArrayList<String>();
-
private String[] lakes;
-
private List<Province> provinces = new ArrayList<Province>();
-
private Map<String, Integer> traffic = new HashMap<String, Integer>();
-
-
public Country() {
-
-
}
-
-
public Country(String countryId) {
-
this.country_id = countryId;
-
}
-
-
public String getCountry_id() {
-
return country_id;
-
}
-
-
public void setCountry_id(String country_id) {
-
this.country_id = country_id;
-
}
-
-
public Date getBirthDate() {
-
return birthDate;
-
}
-
-
public void setBirthDate(Date birthDate) {
-
this.birthDate = birthDate;
-
}
-
-
public List<String> getNation() {
-
return nation;
-
}
-
-
public void setNation(List<String> nation) {
-
this.nation = nation;
-
}
-
-
public String[] getLakes() {
-
return lakes;
-
}
-
-
public void setLakes(String[] lakes) {
-
this.lakes = lakes;
-
}
-
-
public Integer get(String key) {
-
return traffic.get(key);
-
}
-
-
public Map<String, Integer> getTraffic() {
-
return traffic;
-
}
-
-
public void setTraffic(Map<String, Integer> traffic) {
-
this.traffic = traffic;
-
}
-
-
public void addTraffic(String key, Integer value) {
-
traffic.put(key, value);
-
}
-
-
public List<Province> getProvinces() {
-
return provinces;
-
}
-
-
public void setProvinces(List<Province> provinces) {
-
this.provinces = provinces;
-
}
-
-
@Override
-
public String toString() {
-
return "Country [country_id=" + country_id + ", birthDate=" + birthDate
-
+ ", nation=" + nation + ", lakes=" + Arrays.toString(lakes)
-
+ ", province=" + provinces + ", traffic=" + traffic + "]";
-
}
-
-
}
JavaBeanSerializeToJson.java
-
package com.jackson.json.databinding;
-
-
import java.io.File;
-
import java.text.SimpleDateFormat;
-
import java.util.ArrayList;
-
import java.util.List;
-
-
import com.fasterxml.jackson.annotation.JsonInclude.Include;
-
import com.fasterxml.jackson.databind.ObjectMapper;
-
import com.fasterxml.jackson.databind.SerializationFeature;
-
-
public class JavaBeanSerializeToJson {
-
-
public static void convert() throws Exception {
-
-
ObjectMapper mapper = new ObjectMapper();
-
-
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
-
mapper.setDateFormat(dateFormat);
-
-
Country country = new Country("China");
-
country.setBirthDate(dateFormat.parse("1949-10-01"));
-
country.setLakes(new String[] { "Qinghai Lake", "Poyang Lake",
-
"Dongting Lake", "Taihu Lake" });
-
-
List<String> nation = new ArrayList<String>();
-
nation.add("Han");
-
nation.add("Meng");
-
nation.add("Hui");
-
nation.add("WeiWuEr");
-
nation.add("Zang");
-
country.setNation(nation);
-
-
Province province = new Province();
-
province.name = "Shanxi";
-
province.population = 37751200;
-
Province province2 = new Province();
-
province2.name = "ZheJiang";
-
province2.population = 55080000;
-
List<Province> provinces = new ArrayList<Province>();
-
provinces.add(province);
-
provinces.add(province2);
-
country.setProvinces(provinces);
-
-
country.addTraffic("Train(KM)", 112000);
-
country.addTraffic("HighWay(KM)", 4240000);
-
-
mapper.configure(SerializationFeature.INDENT_OUTPUT, true);
-
-
mapper.setSerializationInclusion(Include.NON_EMPTY);
-
-
mapper.writeValue(new File("country.json"), country);
-
}
-
-
public static void main(String[] args) throws Exception {
-
convert();
-
}
-
-
}
After the program runs, country.json is generated, which is as follows:
-
{
-
"country_id" : "China",
-
"birthDate" : "1949-10-01",
-
"nation" : [ "Han", "Meng", "Hui", "WeiWuEr", "Zang" ],
-
"lakes" : [ "Qinghai Lake", "Poyang Lake", "Dongting Lake", "Taihu Lake" ],
-
"provinces" : [ {
-
"name" : "Shanxi",
-
"population" : 37751200
-
}, {
-
"name" : "ZheJiang",
-
"population" : 55080000
-
} ],
-
"traffic" : {
-
"HighWay(KM)" : 4240000,
-
"Train(KM)" : 112000
-
}
-
}
(2) Deserializing Json strings into java objects:
-
package com.jackson.json.databinding;
-
-
import java.io.File;
-
import java.io.IOException;
-
import java.text.SimpleDateFormat;
-
import java.util.Iterator;
-
import java.util.List;
-
-
import com.fasterxml.jackson.core.JsonParseException;
-
import com.fasterxml.jackson.databind.DeserializationFeature;
-
import com.fasterxml.jackson.databind.JsonMappingException;
-
import com.fasterxml.jackson.databind.ObjectMapper;
-
-
-
-
-
public class JsonDeserializeToJava {
-
-
public static void main(String[] args) throws Exception {
-
-
ObjectMapper mapper = new ObjectMapper();
-
File json = new File("country.json");
-
-
-
mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
-
-
-
Country country = mapper.readValue(json, Country.class);
-
System.out.println("country_id:"+country.getCountry_id());
-
-
SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd");
-
String birthDate = dateformat.format(country.getBirthDate());
-
System.out.println("birthDate:"+birthDate);
-
-
List<Province> provinces = country.getProvinces();
-
for (Province province : provinces) {
-
System.out.println("province:"+province.name + "\n" + "population:"+province.population);
-
}
-
}
-
}
The results of program operation are as follows:
-
country_id:China
-
birthDate:1949-10-01
-
province:Shanxi
-
population:37751200
-
province:ZheJiang
-
population:55080000
2.Tree Model Processing Json
(1)tree model generates json:
-
package com.jackson.json.treemodel;
-
-
import java.io.File;
-
import java.io.FileWriter;
-
-
import com.fasterxml.jackson.core.JsonFactory;
-
import com.fasterxml.jackson.core.JsonGenerator;
-
import com.fasterxml.jackson.databind.ObjectMapper;
-
import com.fasterxml.jackson.databind.SerializationFeature;
-
import com.fasterxml.jackson.databind.node.ArrayNode;
-
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
-
import com.fasterxml.jackson.databind.node.ObjectNode;
-
-
public class SerializationExampleTreeModel {
-
-
public static void main(String[] args) throws Exception {
-
-
JsonNodeFactory factory = new JsonNodeFactory(false);
-
-
JsonFactory jsonFactory = new JsonFactory();
-
-
JsonGenerator generator = jsonFactory.createGenerator(new FileWriter(new File("country2.json")));
-
-
ObjectMapper mapper = new ObjectMapper();
-
ObjectNode country = factory.objectNode();
-
-
country.put("country_id", "China");
-
country.put("birthDate", "1949-10-01");
-
-
-
ArrayNode nation = factory.arrayNode();
-
nation.add("Han").add("Meng").add("Hui").add("WeiWuEr").add("Zang");
-
country.set("nation", nation);
-
-
ArrayNode lakes = factory.arrayNode();
-
lakes.add("QingHai Lake").add("Poyang Lake").add("Dongting Lake").add("Taihu Lake");
-
country.set("lakes", lakes);
-
-
ArrayNode provinces = factory.arrayNode();
-
ObjectNode province = factory.objectNode();
-
ObjectNode province2 = factory.objectNode();
-
province.put("name","Shanxi");
-
province.put("population", 37751200);
-
province2.put("name","ZheJiang");
-
province2.put("population", 55080000);
-
provinces.add(province).add(province2);
-
country.set("provinces", provinces);
-
-
ObjectNode traffic = factory.objectNode();
-
traffic.put("HighWay(KM)", 4240000);
-
traffic.put("Train(KM)", 112000);
-
country.set("traffic", traffic);
-
-
mapper.configure(SerializationFeature.INDENT_OUTPUT, true);
-
mapper.writeTree(generator, country);
-
}
-
-
}
The program runs and generates country2.json, which reads as follows:
-
{"country_id":"China","birthDate":"1949-10-01","nation":["Han","Meng","Hui","WeiWuEr","Zang"],"lakes":["QingHai Lake","Poyang Lake","Dongting Lake","Taihu Lake"],"provinces":[{"name":"Shanxi","population":37751200},{"name":"ZheJiang","population":55080000}],"traffic":{"HighWay(KM)":4240000,"Train(KM)":112000}}
(2) json string deserialization to tree mode
Deserialization ExampleTreeModel 1. java, notice the type changes of different JsonNode s in the program
-
package com.jackson.json.treemodel;
-
-
import java.io.File;
-
import java.util.Iterator;
-
-
import com.fasterxml.jackson.databind.JsonNode;
-
import com.fasterxml.jackson.databind.ObjectMapper;
-
-
public class DeserializationExampleTreeModel1 {
-
-
public static void main(String[] args) throws Exception {
-
ObjectMapper mapper = new ObjectMapper();
-
-
JsonNode node = mapper.readTree(new File("country2.json"));
-
-
System.out.println("node JsonNodeType:"+node.getNodeType());
-
-
System.out.println("node is container Node ? "+node.isContainerNode());
-
-
System.out.println("---------Get all node Name of child node of node-------------------------");
-
Iterator<String> fieldNames = node.fieldNames();
-
while (fieldNames.hasNext()) {
-
String fieldName = fieldNames.next();
-
System.out.print(fieldName+" ");
-
}
-
System.out.println("\n-----------------------------------------------------");
-
-
JsonNode country_id = node.get("country_id");
-
System.out.println("country_id:"+country_id.asText() + " JsonNodeType:"+country_id.getNodeType());
-
-
JsonNode birthDate = node.get("birthDate");
-
System.out.println("birthDate:"+birthDate.asText()+" JsonNodeType:"+birthDate.getNodeType());
-
-
JsonNode nation = node.get("nation");
-
System.out.println("nation:"+ nation+ " JsonNodeType:"+nation.getNodeType());
-
-
JsonNode lakes = node.get("lakes");
-
System.out.println("lakes:"+lakes+" JsonNodeType:"+lakes.getNodeType());
-
-
JsonNode provinces = node.get("provinces");
-
System.out.println("provinces JsonNodeType:"+provinces.getNodeType());
-
-
boolean flag = true;
-
for (JsonNode provinceElements : provinces) {
-
-
if(flag){
-
System.out.println("provinceElements JsonNodeType:"+provinceElements.getNodeType());
-
System.out.println("provinceElements is container node? "+provinceElements.isContainerNode());
-
flag = false;
-
}
-
Iterator<String> provinceElementFields = provinceElements.fieldNames();
-
while (provinceElementFields.hasNext()) {
-
String fieldName = (String) provinceElementFields.next();
-
String province;
-
if ("population".equals(fieldName)) {
-
province = fieldName + ":" + provinceElements.get(fieldName).asInt();
-
}else{
-
province = fieldName + ":" + provinceElements.get(fieldName).asText();
-
}
-
System.out.println(province);
-
}
-
}
-
}
-
}
After running the program, the printing results are as follows:
-
node JsonNodeType:OBJECT
-
node is container Node ? true
-
---------Get all node Name of child node of node-------------------------
-
country_id birthDate nation lakes provinces traffic
-
-----------------------------------------------------
-
country_id:China JsonNodeType:STRING
-
birthDate:1949-10-01 JsonNodeType:STRING
-
nation:["Han","Meng","Hui","WeiWuEr","Zang"] JsonNodeType:ARRAY
-
lakes:["QingHai Lake","Poyang Lake","Dongting Lake","Taihu Lake"] JsonNodeType:ARRAY
-
provinces JsonNodeType:ARRAY
-
provinceElements JsonNodeType:OBJECT
-
provinceElements is container node? true
-
name:Shanxi
-
population:37751200
-
name:ZheJiang
-
population:55080000
Let's look at Deserialization ExampleTreeModel 2. java. In this case, we use the JsonNode.path method, which is similar to the get method used in Deserialization ExampleTreeModel 1. java.
But when the node does not exist, the get method returns null, while the path returns JsonNode of MISSING type.
-
package com.jackson.json.treemodel;
-
-
import java.io.File;
-
import java.io.IOException;
-
import java.util.Iterator;
-
-
import com.fasterxml.jackson.core.JsonProcessingException;
-
import com.fasterxml.jackson.databind.JsonNode;
-
import com.fasterxml.jackson.databind.ObjectMapper;
-
-
public class DeserializationExampleTreeModle2 {
-
-
public static void main(String[] args) throws JsonProcessingException, IOException{
-
ObjectMapper mapper = new ObjectMapper();
-
JsonNode node = mapper.readTree(new File("country2.json"));
-
-
JsonNode missingNode = node.path("test");
-
if(missingNode.isMissingNode()){
-
System.out.println("JsonNodeType : " + missingNode.getNodeType());
-
}
-
-
System.out.println("country_id:"+node.path("country_id").asText());
-
-
JsonNode provinces = node.path("provinces");
-
for (JsonNode provinceElements : provinces) {
-
Iterator<String> provincesFields = provinceElements.fieldNames();
-
while (provincesFields.hasNext()) {
-
String fieldName = (String) provincesFields.next();
-
String province;
-
if("name".equals(fieldName)){
-
province = fieldName +":"+ provinceElements.path(fieldName).asText();
-
}else{
-
province = fieldName +":"+ provinceElements.path(fieldName).asInt();
-
}
-
System.out.println(province);
-
}
-
}
-
}
-
-
}
The program runs and prints the result:
-
JsonNodeType : MISSING
-
country_id:China
-
name:Shanxi
-
population:37751200
-
name:ZheJiang
-
population:55080000
3.Stream handles Json
(1)stream generation json
-
package com.jackson.json.streaming;
-
-
import java.io.File;
-
import java.io.FileWriter;
-
import java.io.Exception;
-
-
import com.fasterxml.jackson.core.JsonFactory;
-
import com.fasterxml.jackson.core.JsonGenerator;
-
-
public class StreamGeneratorJson {
-
-
public static void main(String[] args) throws Exception {
-
JsonFactory factory = new JsonFactory();
-
-
JsonGenerator generator = factory.createGenerator(new FileWriter(new File("country3.json")));
-
-
generator.writeStartObject();
-
generator.writeFieldName("country_id");
-
generator.writeString("China");
-
generator.writeFieldName("provinces");
-
generator.writeStartArray();
-
generator.writeStartObject();
-
generator.writeStringField("name", "Shanxi");
-
generator.writeNumberField("population", 33750000);
-
generator.writeEndObject();
-
generator.writeEndArray();
-
generator.writeEndObject();
-
-
generator.close();
-
}
-
-
}
After the program runs, country3.json file content is generated:
-
{"country_id":"China","provinces":[{"name":"Shanxi","population":33750000}]}
(2)stream parsing json:
Now adgcountry3.json, we use the Streaming API to parse the above Json and find the value of population in json.
-
package com.jackson.json.streaming;
-
-
import java.io.File;
-
import java.io.IOException;
-
-
import com.fasterxml.jackson.core.JsonFactory;
-
import com.fasterxml.jackson.core.JsonParseException;
-
import com.fasterxml.jackson.core.JsonParser;
-
import com.fasterxml.jackson.core.JsonToken;
-
-
-
-
-
public class StreamParserJson {
-
public static void main(String[] args) throws JsonParseException,
-
IOException {
-
JsonFactory factory = new JsonFactory();
-
-
JsonParser parser = factory.createParser(new File("country3.json"));
-
-
while (!parser.isClosed()) {
-
-
JsonToken token = parser.nextToken();
-
if (token == null) {
-
break;
-
}
-
-
-
if (JsonToken.FIELD_NAME.equals(token)
-
&& "provinces".equals(parser.getCurrentName())) {
-
token = parser.nextToken();
-
if (!JsonToken.START_ARRAY.equals(token)) {
-
break;
-
}
-
-
token = parser.nextToken();
-
if (!JsonToken.START_OBJECT.equals(token)) {
-
break;
-
}
-
while (true) {
-
token = parser.nextToken();
-
if (token == null) {
-
break;
-
}
-
if (JsonToken.FIELD_NAME.equals(token)
-
&& "population".equals(parser.getCurrentName())) {
-
token = parser.nextToken();
-
System.out.println(parser.getCurrentName() + " : "
-
+ parser.getIntValue());
-
}
-
}
-
}
-
}
-
}
-
-
}
After the program runs, the results are printed in the console as follows:
summary
In the example above, I have dealt with Json in three ways. My experience is as follows:
Stream API has the lowest overhead and the highest efficiency, but it also has the highest coding complexity. When generating Json, we need to write symbols and field splicing JSON step by step. When parsing Json, we need to find JSON values according to token pointing. It is not convenient to generate and parse json, and the code readability is also low.
Data binding is the most commonly used method of JSON processing. When generating json, we create relevant java objects, assemble them according to JSON content structure, and finally call the writeValue method to generate json.
When parsing, it is simpler to map json directly to the relevant java objects, and then you can traverse the java objects to get the values.
TreeModel deals with Json. It generates and parses JSON by tree structure. When generating json, according to JSON content structure, we create different types of node objects and assemble these nodes to generate json. When parsing json, it does not need to bind JSON to Java beans. According to JSON structure, it can easily find content by path or get method.
Learning reference: http://www.cnblogs.com/lee0oo0/articles/2652528.html