Jackson序列化和反序列化Json数据
Web技术发展的今天,Json和XML已经成为了web数据的事实标准,然而这种格式化的数据手工解析又非常麻烦,软件工程界永远不缺少工具,每当有需求的时候就会出现各种类库,框架以及工具来解决这些基础的问题,Jackson就是这些工具中的一个,使用这个工具开发者完全可以从手工结束Json数据的重复劳动中解放出来。使用Jackson首先需要下载相应的类库,如下的Maven dependency列出了完整的POM dependency。
1 <dependency>View Code
2 <groupId>com.fasterxml.jackson.core</groupId>
3 <artifactId>jackson-core</artifactId>
4 <version>${jackson-2-version}</version>
5 </dependency>
6
7 <!-- Just the annotations; use this dependency if you want to attach annotations
8 to classes without connecting them to the code. -->
9 <dependency>
10 <groupId>com.fasterxml.jackson.core</groupId>
11 <artifactId>jackson-annotations</artifactId>
12 <version>${jackson-2-version}</version>
13 </dependency>
14
15 <!-- databinding; ObjectMapper, JsonNode and related classes are here -->
16 <dependency>
17 <groupId>com.fasterxml.jackson.core</groupId>
18 <artifactId>jackson-databind</artifactId>
19 <version>${jackson-2-version}</version>
20 </dependency>
21
22 <!-- smile (binary JSON). Other artifacts in this group do other formats. -->
23 <dependency>
24 <groupId>com.fasterxml.jackson.dataformat</groupId>
25 <artifactId>jackson-dataformat-smile</artifactId>
26 <version>${jackson-2-version}</version>
27 </dependency>
28 <!-- JAX-RS provider -->
29 <dependency>
30 <groupId>com.fasterxml.jackson.jaxrs</groupId>
31 <artifactId>jackson-jaxrs-json-provider</artifactId>
32 <version>${jackson-2-version}</version>
33 </dependency>
34 <!-- Support for JAX-B annotations as additional configuration -->
35 <dependency>
36 <groupId>com.fasterxml.jackson.module</groupId>
37 <artifactId>jackson-module-jaxb-annotations</artifactId>
38 <version>${jackson-2-version}</version>
39 </dependency>
比如我们需要解析的Json数据如下:
{
"id": 123,
"name": "Pankaj",
"permanent": true,
"address": {
"street": "Albany Dr",
"city": "San Jose",
"zipcode": 95129
},
"phoneNumbers": [
123456,
987654
],
"role": "Manager",
"cities": [
"Los Angeles",
"New York"
],
"properties": {
"age": "29 years",
"salary": "1000 USD"
}
}
对应的Model Class 如下:
import java.util.Arrays;
import java.util.List;
import java.util.Map;
public class Employee {
private int id;
private String name;
private boolean permanent;
private Address address;
private long[] phoneNumbers;
private String role;
private List<String> cities;
private Map<String, String> properties;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean isPermanent() {
return permanent;
}
public void setPermanent(boolean permanent) {
this.permanent = permanent;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public long[] getPhoneNumbers() {
return phoneNumbers;
}
public void setPhoneNumbers(long[] phoneNumbers) {
this.phoneNumbers = phoneNumbers;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
@Override
public String toString(){
StringBuilder sb = new StringBuilder();
sb.append("***** Employee Details *****\n");
sb.append("ID="+getId()+"\n");
sb.append("Name="+getName()+"\n");
sb.append("Permanent="+isPermanent()+"\n");
sb.append("Role="+getRole()+"\n");
sb.append("Phone Numbers="+Arrays.toString(getPhoneNumbers())+"\n");
sb.append("Address="+getAddress()+"\n");
sb.append("Cities="+Arrays.toString(getCities().toArray())+"\n");
sb.append("Properties="+getProperties()+"\n");
sb.append("*****************************");
return sb.toString();
}
public List<String> getCities() {
return cities;
}
public void setCities(List<String> cities) {
this.cities = cities;
}
public Map<String, String> getProperties() {
return properties;
}
public void setProperties(Map<String, String> properties) {
this.properties = properties;
}
}
当我们需要操作Json数据的时候,如下代码示范了如何将Json数据反序列化为对象以及如何将对象序列化为Json数据。
import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.node.ObjectNode;
public class JacksonObjectMapperExample {
public static void main(String[] args) throws IOException {
//read json file data to String
byte[] jsonData = Files.readAllBytes(Paths.get("C:\\employee.txt"));
//create ObjectMapper instance
ObjectMapper objectMapper = new ObjectMapper();
//convert json string to object
Employee emp = objectMapper.readValue(jsonData, Employee.class);
System.out.println("Employee Object\n"+emp);
//convert Object to json string
Employee emp1 = createEmployee();
//configure Object mapper for pretty print
objectMapper.configure(SerializationFeature.INDENT_OUTPUT, true);
//writing to console, can write to any output stream such as file
StringWriter stringEmp = new StringWriter();
objectMapper.writeValue(stringEmp, emp1);
System.out.println("Employee JSON is\n"+stringEmp);
}
public static Employee createEmployee() {
Employee emp = new Employee();
emp.setId(100);
emp.setName("David");
emp.setPermanent(false);
emp.setPhoneNumbers(new long[] { 123456, 987654 });
emp.setRole("Manager");
Address add = new Address();
add.setCity("Bangalore");
add.setStreet("BTM 1st Stage");
add.setZipcode(560100);
emp.setAddress(add);
List<String> cities = new ArrayList<String>();
cities.add("Los Angeles");
cities.add("New York");
emp.setCities(cities);
Map<String, String> props = new HashMap<String, String>();
props.put("salary", "1000 Rs");
props.put("age", "28 years");
emp.setProperties(props);
return emp;
}
}
结果如下:
Employee Object
***** Employee Details *****
ID=123
Name=Pankaj
Permanent=true
Role=Manager
Phone Numbers=[123456, 987654]
Address=Albany Dr, San Jose, 95129
Cities=[Los Angeles, New York]
Properties={age=29 years, salary=1000 USD}
*****************************
Employee JSON is
{
"id" : 100,
"name" : "David",
"permanent" : false,
"address" : {
"street" : "BTM 1st Stage",
"city" : "Bangalore",
"zipcode" : 560100
},
"phoneNumbers" : [ 123456, 987654 ],
"role" : "Manager",
"cities" : [ "Los Angeles", "New York" ],
"properties" : {
"salary" : "1000 Rs",
"age" : "28 years"
}
}
总结
本文以一个完整的示例总结了Java对象序列化为Json对象和反序列化的过程,希望可以抛砖引玉对大家有所帮助。