Jackson序列化和反序列化Json数据
Web技术发展的今天,Json和XML已经成为了web数据的事实标准,然而这种格式化的数据手工解析又非常麻烦,软件工程界永远不缺少工具,每当有需求的时候就会出现各种类库,框架以及工具来解决这些基础的问题,Jackson就是这些工具中的一个,使用这个工具开发者完全可以从手工结束Json数据的重复劳动中解放出来。使用Jackson首先需要下载相应的类库,如下的Maven dependency列出了完整的POM dependency。
12 6 7 9com.fasterxml.jackson.core 3jackson-core 4${jackson-2-version} 510 14 15 16com.fasterxml.jackson.core 11jackson-annotations 12${jackson-2-version} 1317 21 22 23com.fasterxml.jackson.core 18jackson-databind 19${jackson-2-version} 2024 28 29com.fasterxml.jackson.dataformat 25jackson-dataformat-smile 26${jackson-2-version} 2730 34 35com.fasterxml.jackson.jaxrs 31jackson-jaxrs-json-provider 32${jackson-2-version} 3336 com.fasterxml.jackson.module 37jackson-module-jaxb-annotations 38${jackson-2-version} 39
比如我们需要解析的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 Listcities; private Map 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 getCities() { return cities; } public void setCities(List cities) { this.cities = cities; } public Map getProperties() { return properties; } public void setProperties(Map 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); Listcities = new ArrayList (); cities.add("Los Angeles"); cities.add("New York"); emp.setCities(cities); Map props = new HashMap (); props.put("salary", "1000 Rs"); props.put("age", "28 years"); emp.setProperties(props); return emp; } }
结果如下:
Employee Object***** Employee Details *****ID=123Name=PankajPermanent=trueRole=ManagerPhone Numbers=[123456, 987654]Address=Albany Dr, San Jose, 95129Cities=[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对象和反序列化的过程,希望可以抛砖引玉对大家有所帮助。