很多时候,我们需要在JSON string和java object之间进行转换,如,将web service Request中的JSON string转化为java object进行处理,然后将得到的java object转化为JSON string封装进Response。
Jackson library提供了这个功能。这里提供了jackson tutorial,本文时读取该tutorial的笔记。
优点:1. jackson为大多数java objects提供了默认的mapping;2. jackson速度快,使用内存小; 3. 不依赖于JDK之外的library;4. 开源。
jackson提供3种方式来处理JSON。
1. Streaming API - 将读写son作为分离的事件,JsonParser读数据,JsonGenerator写数据。三种方法中最流行的,性能开销最低,速度最快,类似于XML的Stax parser;
2. Tree Model - 在内存中维护tree来表示JSON document. ObjectMapper构建由JsonNode构成的tree,是最灵活的方法,类似于XML的DOM parser;
3. Data Binding - 使用property accessor或annotations来在JSON和Plain Old Java Object (POJO)之间转换。ObjectMapper使用这两种方法来读写JSON。Data binding类似于XML的JAXB parser.
Preparation: 需要在project中加载external lib jackson-all-1.9.0.jar.
Example:
1. Create java object - Student
2. Create main class
public class JacksonTestMain {
public static void main(String[] args) {
ObjectMapper mapper = new ObjectMapper();
String jsonString = "{\"name\":\"Mahesh\",\"age\":21}";
try {
//map json string to object
Student student = mapper.readValue(jsonString, Student.class);
System.out.println(student);
//map object to json string
String jsonResult = mapper.writeValueAsString(student);
System.out.println(jsonResult);
} catch (JsonParseException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
执行该程序,得到下面的结果。
Output:
Student [name=Mahesh, age=21]
{"name":"Mahesh","age":21}
上面我们已经实现JSON string与java object之间的转换。
ObjectMapper是jackson library中的主要类,使用JsonParser和JsonGenerator来在JSON string与java object之间进行转换。readValue将JSON string转化为java object,writeValueAsString将java object转化为JSON string。
Tree Model:
Create tree from JSON
ObjectMapper mapper = new ObjectMapper();
String jsonString = "{\"name\":\"Mahesh Kumar\", \"age\":21,\"verified\":false,\"marks\": [100,90,85]}";
//create tree from JSON
JsonNode rootNode = mapper.readTree(jsonString);
Traversing a Tree
JsonNode nameNode = rootNode.path("name");
System.out.println("Name: "+ nameNode.getTextValue());
JsonNode marksNode = rootNode.path("marks");
Iterator iterator = marksNode.getElements();
Convert Tree to JSON
ObjectMapper mapper = new ObjectMapper();
JsonNode rootNode = mapper.createObjectNode();
JsonNode marksNode = mapper.createArrayNode();
((ArrayNode)marksNode).add(100);
((ArrayNode)marksNode).add(90);
((ArrayNode)marksNode).add(85);
((ObjectNode) rootNode).put("name", "Mahesh Kumar");
((ObjectNode) rootNode).put("age", 21);
((ObjectNode) rootNode).put("verified", false);
((ObjectNode) rootNode).put("marks",marksNode);
mapper.writeValue(new File("student.json"), rootNode);
Tree to Object
Student student = mapper.treeToValue(rootNode, Student.class);
Streaming API
write to JSON - JsonGenerator
JsonFactory jasonFactory = new JsonFactory();
JsonGenerator jsonGenerator = jasonFactory.createJsonGenerator(new File("student.json"), JsonEncoding.UTF8);
// {
jsonGenerator.writeStartObject();
// "name" : "Mahesh Kumar"
jsonGenerator.writeStringField("name", "Mahesh Kumar");
// "age" : 21
jsonGenerator.writeNumberField("age", 21);
// "verified" : false
jsonGenerator.writeBooleanField("verified", false);
// "marks" : [100, 90, 85]
jsonGenerator.writeFieldName("marks");
// [
jsonGenerator.writeStartArray();
// 100, 90, 85
jsonGenerator.writeNumber(100);
jsonGenerator.writeNumber(90);
jsonGenerator.writeNumber(85);
// ]
jsonGenerator.writeEndArray();
// }
jsonGenerator.writeEndObject();
jsonGenerator.close();
Reading JSON - jsonParser
JsonParser jsonParser = jasonFactory.createJsonParser(new File("student.json"));
while (jsonParser.nextToken() != JsonToken.END_OBJECT) {
//get the current token
String fieldname = jsonParser.getCurrentName();
if ("name".equals(fieldname)) {
//move to next token
jsonParser.nextToken();
System.out.println(jsonParser.getText());
}
if("age".equals(fieldname)){
//move to next token
jsonParser.nextToken();
System.out.println(jsonParser.getNumberValue());
}
if("verified".equals(fieldname)){
//move to next token
jsonParser.nextToken();
System.out.println(jsonParser.getBooleanValue());
}
if("marks".equals(fieldname)){
//move to [
jsonParser.nextToken();
// loop till token equal to "]"
while (jsonParser.nextToken() != JsonToken.END_ARRAY) {
System.out.println(jsonParser.getNumberValue());
}
}
}