博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Jackson序列化和反序列化Json数据完整示例
阅读量:6295 次
发布时间:2019-06-22

本文共 7263 字,大约阅读时间需要 24 分钟。

Jackson序列化和反序列化Json数据

Web技术发展的今天,Json和XML已经成为了web数据的事实标准,然而这种格式化的数据手工解析又非常麻烦,软件工程界永远不缺少工具,每当有需求的时候就会出现各种类库,框架以及工具来解决这些基础的问题,Jackson就是这些工具中的一个,使用这个工具开发者完全可以从手工结束Json数据的重复劳动中解放出来。使用Jackson首先需要下载相应的类库,如下的Maven dependency列出了完整的POM dependency。

1         
2
com.fasterxml.jackson.core
3
jackson-core
4
${jackson-2-version}
5
6 7
9
10
com.fasterxml.jackson.core
11
jackson-annotations
12
${jackson-2-version}
13
14 15
16
17
com.fasterxml.jackson.core
18
jackson-databind
19
${jackson-2-version}
20
21 22
23
24
com.fasterxml.jackson.dataformat
25
jackson-dataformat-smile
26
${jackson-2-version}
27
28
29
30
com.fasterxml.jackson.jaxrs
31
jackson-jaxrs-json-provider
32
${jackson-2-version}
33
34
35
36
com.fasterxml.jackson.module
37
jackson-module-jaxb-annotations
38
${jackson-2-version}
39
View Code

比如我们需要解析的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
cities; 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);         List
cities = 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对象和反序列化的过程,希望可以抛砖引玉对大家有所帮助。

转载地址:http://ntpta.baihongyu.com/

你可能感兴趣的文章
JavaScript—数组(17)
查看>>
Android 密钥保护和 C/S 网络传输安全理论指南
查看>>
以太坊ERC20代币合约优化版
查看>>
Why I Began
查看>>
同一台电脑上Windows 7和Ubuntu 14.04的CPU温度和GPU温度对比
查看>>
js数组的操作
查看>>
springmvc Could not write content: No serializer
查看>>
Python系语言发展综述
查看>>
新手 开博
查看>>
借助开源工具高效完成Java应用的运行分析
查看>>
163 yum
查看>>
第三章:Shiro的配置——深入浅出学Shiro细粒度权限开发框架
查看>>
80后创业的经验谈(转,朴实但实用!推荐)
查看>>
让Windows图片查看器和windows资源管理器显示WebP格式
查看>>
我的友情链接
查看>>
vim使用点滴
查看>>
embedded linux学习中几个需要明确的概念
查看>>
mysql常用语法
查看>>
Morris ajax
查看>>
【Docker学习笔记(四)】通过Nginx镜像快速搭建静态网站
查看>>