Jackson 使用和注意项
依赖maven:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.6.5</version>
</dependency> <dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.6.5</version>
</dependency> <dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.6.5</version>
</dependency>
code:
User:
import lombok.*; @Data
@ToString
@NoArgsConstructor
@AllArgsConstructor
public class User {
private int id;
private String name;
private String email;
private String address;
private Birthday birthday;
}
Birthday:
import lombok.*; @Data
@ToString
@NoArgsConstructor
@AllArgsConstructor
public class Birthday {
private String birthday;
}
User2:
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString; @Data
@ToString
@NoArgsConstructor
@AllArgsConstructor
public class User2 {
private int id;
private String name;
private String email;
// private String address;
// private Birthday birthday;
}
1.查看基础类型的序列化与反序列化:
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.val; import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map; public class test{ private final static ObjectMapper objectMapper = new ObjectMapper(); public static void main(String[] args) { User user = new User();
user.setAddress("asdf");
user.setAddress("中国河南省");
user.setEmail("xiaokui_wingfly@sina.com.cn");
user.setId(1);
user.setName("X-rapido");
user.setBirthday(new Birthday("2015-08-06")); List<String> list = new ArrayList<String>();
list.add("a");
list.add("b");
list.add("c"); Map<String, Object> map = new HashMap<String, Object>();
map.put("a", "1");
map.put("b", "2");
map.put("c", "3");
map.put("list", list); String []sz = {"a","b","c"}; try {
System.out.println(objectMapper.writeValueAsString(user));
System.out.println(objectMapper.writeValueAsString(list));
System.out.println(objectMapper.writeValueAsString(map));
System.out.println(objectMapper.writeValueAsString(sz)); String s = "{\"name\":\"X-rapido\"}";
// Json转换JavaBean
User a = objectMapper.readValue(s, User.class);
System.out.println(a.getName()); // JavaBean转换Json
System.out.println(objectMapper.writeValueAsString(a));
} catch (IOException e) {
e.printStackTrace();
}
}
}
Output:
{"id":1,"name":"X-rapido","email":"xiaokui_wingfly@sina.com.cn","address":"中国河南省","birthday":{"birthday":"2015-08-06"}}
["a","b","c"]
{"a":"1","b":"2","c":"3","list":["a","b","c"]}
["a","b","c"]
X-rapido
{"id":0,"name":"X-rapido","email":null,"address":null,"birthday":null}
2.有这么种情况,就是字符串反序列化为对象,但是字符串中的很多字段我都不需要,只需要一部分,这个时候怎么反序列化:
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.val; import java.io.IOException; public class test{ private final static ObjectMapper objectMapper = new ObjectMapper();
public static void main(String[] args) { //当反序列化json时,未知属性会引起的反序列化被打断,这里我们禁用未知属性打断反序列化功能,
//因为,例如json里有10个属性,而我们的bean中只定义了2个属性,其它8个属性将被忽略
objectMapper .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); User user = new User();
user.setAddress("asdf");
user.setAddress("中国河南省");
user.setEmail("xiaokui_wingfly@sina.com.cn");
user.setId(1);
user.setName("X-rapido");
user.setBirthday(new Birthday("2015-08-06")); try {
System.out.println("========begin=======");
val content=objectMapper.writeValueAsString(user);
System.out.println(content);
User2 u=objectMapper.readValue(content,User2.class);
System.out.println(objectMapper.writeValueAsString(u));
System.out.println("========end======="); } catch (IOException e) {
e.printStackTrace();
}
}
}
Output:
========begin=======
{"id":1,"name":"X-rapido","email":"xiaokui_wingfly@sina.com.cn","address":"中国河南省","birthday":{"birthday":"2015-08-06"}}
{"id":1,"name":"X-rapido","email":"xiaokui_wingfly@sina.com.cn"}
========end=======
注意:
objectMapper .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
如果不加这个会报错:
========begin=======
{"id":1,"name":"X-rapido","email":"xiaokui_wingfly@sina.com.cn","address":"中国河南省","birthday":{"birthday":"2015-08-06"}}
com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "address" (class com.qhong.json.User2), not marked as ignorable (3 known properties: "id", "email", "name"])
at [Source: {"id":1,"name":"X-rapido","email":"xiaokui_wingfly@sina.com.cn","address":"中国河南省","birthday":{"birthday":"2015-08-06"}}; line: 1, column: 76] (through reference chain: com.qhong.json.User2["address"])
at com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException.from(UnrecognizedPropertyException.java:51)
at com.fasterxml.jackson.databind.DeserializationContext.reportUnknownProperty(DeserializationContext.java:839)
at com.fasterxml.jackson.databind.deser.std.StdDeserializer.handleUnknownProperty(StdDeserializer.java:1045)
at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.handleUnknownProperty(BeanDeserializerBase.java:1352)
at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.handleUnknownVanilla(BeanDeserializerBase.java:1330)
at com.fasterxml.jackson.databind.deser.BeanDeserializer.vanillaDeserialize(BeanDeserializer.java:264)
at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:125)
at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:3736)
at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2726)
at com.qhong.json.test.main(test.java:29)
3.怎么反序列化对象数组:
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.val; import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List; public class test{
private final static ObjectMapper objectMapper = new ObjectMapper();
public static void main(String[] args) {
//当反序列化json时,未知属性会引起的反序列化被打断,这里我们禁用未知属性打断反序列化功能,
//因为,例如json里有10个属性,而我们的bean中只定义了2个属性,其它8个属性将被忽略
objectMapper .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); List<User> arr= Arrays.asList(
new User(1, "name1", "email1", "address1", new Birthday("2016-08-01")),
new User(2 ,"name2", "email2", "address2", new Birthday("2016-08-02")),
new User(3, "name3", "email3", "address3", new Birthday("2016-08-03"))
); try {
System.out.println("========begin=======");
val content=objectMapper.writeValueAsString(arr);
System.out.println(content);
List<User> list=objectMapper.readValue(content,new com.fasterxml.jackson.core.type.TypeReference<List<User>>(){});
System.out.println(objectMapper.writeValueAsString(list));
System.out.println("另外的方式:");
// List<MyClass> myObjects = mapper.readValue(jsonInput, mapper.getTypeFactory().constructCollectionType(List.class, MyClass.class));
List<User> list2=objectMapper.readValue(content,objectMapper.getTypeFactory().constructCollectionType(ArrayList.class,User.class));
System.out.println(objectMapper.writeValueAsString(list2));
System.out.println("========end======="); } catch (IOException e) {
e.printStackTrace();
}
}
}
Output:
========begin=======
[{"id":1,"name":"name1","email":"email1","address":"address1","birthday":{"birthday":"2016-08-01"}},{"id":2,"name":"name2","email":"email2","address":"address2","birthday":{"birthday":"2016-08-02"}},{"id":3,"name":"name3","email":"email3","address":"address3","birthday":{"birthday":"2016-08-03"}}]
[{"id":1,"name":"name1","email":"email1","address":"address1","birthday":{"birthday":"2016-08-01"}},{"id":2,"name":"name2","email":"email2","address":"address2","birthday":{"birthday":"2016-08-02"}},{"id":3,"name":"name3","email":"email3","address":"address3","birthday":{"birthday":"2016-08-03"}}]
另外的方式:
[{"id":1,"name":"name1","email":"email1","address":"address1","birthday":{"birthday":"2016-08-01"}},{"id":2,"name":"name2","email":"email2","address":"address2","birthday":{"birthday":"2016-08-02"}},{"id":3,"name":"name3","email":"email3","address":"address3","birthday":{"birthday":"2016-08-03"}}]
========end=======
还有一些其他的特殊情况,比如json对象key没有双引号等
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
import java.util.List; public class test2{
private final static ObjectMapper mapper= new ObjectMapper();
public static void main(String[] args) {
try {
mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
// 如果为空则不输出
mapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
// 对于空的对象转json的时候不抛出错误
mapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
// 禁用序列化日期为timestamps
mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
// 禁用遇到未知属性抛出异常
mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
// 视空字符传为null
mapper.enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT); // 低层级配置
mapper.configure(JsonParser.Feature.ALLOW_COMMENTS, true);
// 允许属性名称没有引号
mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
// 允许单引号
mapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
// 取消对非ASCII字符的转码
mapper.configure(JsonGenerator.Feature.ESCAPE_NON_ASCII, false); //mapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
String str = " [\n" +
" {\n" +
" \"symbol\": \"sh603111\", \n" +
" \"code\": \"603111\", \n" +
" \"name\": \"康尼机电\", \n" +
" \"trade\": \"14.530\", \n" +
" \"pricechange\": \"0.770\", \n" +
" \"changepercent\": \"5.596\", \n" +
" \"buy\": \"14.530\", \n" +
" \"sell\": \"14.540\", \n" +
" \"settlement\": \"13.760\", \n" +
" \"open\": \"13.820\", \n" +
" \"high\": \"14.540\", \n" +
" \"low\": \"13.820\", \n" +
" \"volume\": 18591408, \n" +
" \"amount\": 266138177, \n" +
" \"ticktime\": \"15:00:00\", \n" +
" \"per\": 44.339, \n" +
" \"pb\": 7.731, \n" +
" \"mktcap\": 1072870.86225, \n" +
" \"nmc\": 697004.688465, \n" +
" \"turnoverratio\": 3.87563\n" +
" }, \n" +
" {\n" +
" \"symbol\": \"sz300355\", \n" +
" \"code\": \"300355\", \n" +
" \"name\": \"蒙草生态\", \n" +
" \"trade\": \"12.330\", \n" +
" \"pricechange\": \"0.620\", \n" +
" \"changepercent\": \"5.295\", \n" +
" \"buy\": \"12.330\", \n" +
" \"sell\": \"12.340\", \n" +
" \"settlement\": \"11.710\", \n" +
" \"open\": \"11.640\", \n" +
" \"high\": \"12.580\", \n" +
" \"low\": \"11.640\", \n" +
" \"volume\": 142839605, \n" +
" \"amount\": 1741652819, \n" +
" \"ticktime\": \"15:06:03\", \n" +
" \"per\": 35.229, \n" +
" \"pb\": 6.27, \n" +
" \"mktcap\": 1978030.485873, \n" +
" \"nmc\": 1428385.32288, \n" +
" \"turnoverratio\": 12.33009\n" +
" }\n" +
"]";
System.out.println(str);
List<riseInfo> list = mapper.readValue(str, new TypeReference<List<riseInfo>>() {
});
System.out.println(list.size());
}catch (Exception ex){
System.out.println(ex.getMessage());
System.out.println(ex.getStackTrace());
}
}
} @Data
@ToString
@NoArgsConstructor
@AllArgsConstructor
class riseInfo {
private String symbol;
private String code;
private String name;
}
Output:
[
{
"symbol": "sh603111",
"code": "",
"name": "康尼机电",
"trade": "14.530",
"pricechange": "0.770",
"changepercent": "5.596",
"buy": "14.530",
"sell": "14.540",
"settlement": "13.760",
"open": "13.820",
"high": "14.540",
"low": "13.820",
"volume": ,
"amount": ,
"ticktime": "15:00:00",
"per": 44.339,
"pb": 7.731,
"mktcap": 1072870.86225,
"nmc": 697004.688465,
"turnoverratio": 3.87563
},
{
"symbol": "sz300355",
"code": "",
"name": "蒙草生态",
"trade": "12.330",
"pricechange": "0.620",
"changepercent": "5.295",
"buy": "12.330",
"sell": "12.340",
"settlement": "11.710",
"open": "11.640",
"high": "12.580",
"low": "11.640",
"volume": ,
"amount": ,
"ticktime": "15:06:03",
"per": 35.229,
"pb": 6.27,
"mktcap": 1978030.485873,
"nmc": 1428385.32288,
"turnoverratio": 12.33009
}
]
添加配置即可!
http://blog.csdn.net/langzi7758521/article/details/52072457
http://www.cnblogs.com/kakag/p/5054772.html
http://www.cnblogs.com/dupang/p/5673097.html
https://codeday.me/bug/20170221/3548.html
Jackson 使用和注意项的更多相关文章
- 使用jackson对Java对象与JSON字符串相互转换的一些总结
本文为菠萝大象原创,如要转载请注明出处.http://www.blogjava.net/bolo 代码无真相,为了最简单的说明,我直接上代码. public class User { private ...
- jackson的简单实用实例(json)
一个json格式的字符串比如: {"status":10001,"code":"HDkGzI","pubkey":&qu ...
- JSON(三)——java中对于JSON格式数据的解析之json-lib与jackson
java中对于JSON格式数据的操作,主要是json格式字符串与JavaBean之间的相互转换.java中能够解析JSON格式数据的框架有很多,比如json-lib,jackson,阿里巴巴的fast ...
- Jackson解析XML
使用Jackson maven项目的pom.xml依赖 <dependency> <groupId>com.fasterxml.jackson.dataformat</g ...
- Jackson 工具类使用及配置指南
目录 前言 Jackson使用工具类 Jackson配置属性 Jackson解析JSON数据 Jackson序列化Java对象 前言 Json数据格式这两年发展的很快,其声称相对XML格式有很对好处: ...
- JSON类库Jackson与JSON-lib性能对比[转]
Jackson:http://jackson.codehaus.org/ JSON-lib:http://json-lib.sourceforge.net/ Gson:http://code.goog ...
- Jackson工具类使用及配置指南、高性能配置(转)
Jackson使用工具类 通常,我们对JSON格式的数据,只会进行解析和封装两种,也就是JSON字符串--->Java对象以及Java对象--->JSON字符串. public class ...
- 两款JSON类库Jackson与JSON-lib的性能对比(新增第三款测试)
本篇文章主要介绍了"两款JSON类库Jackson与JSON-lib的性能对比(新增第三款测试)",主要涉及到两款JSON类库Jackson与JSON-lib的性能对比(新增第三款 ...
- jackson 进行json与java对象转换 之一
代码无真相,为了最简单的说明,我直接上代码. public class User { private String name; private Gender gender; private List& ...
随机推荐
- 64位windows 7下配置TortoiseGit(转)
原文:http://our2848884.blog.163.com/blog/static/146854834201152325233854/ 最近感觉自己电脑上的代码太乱了,东一块.西一块……于是决 ...
- grunt学习二
1. 新建文件和文件目录 mkdir grunt-in-action cd grunt-in-action cd grunt-in-action mkdir grunt-empty cd grunt- ...
- android(七)Looper Handler分析
一.总结 Looper有一个MessageQueue,用于封装消息循环. Handler封装了消息投递,消息处理等的辅助类 二.分析 1.从Looper的用法开始分析 class LooperTh ...
- 群用户通过微信小程序可以更好地协作了
今天,小程序向开发者开放了群ID的接口能力.简单地说,就是当你把小程序分享在群聊中,被点击后开发者可获取群ID和群名称,也方便更好地针对群场景提供个性化服务.不同的群有各自的群ID,那么这个新能力开发 ...
- 最简单的css实现页面宽度自适应
<div class="rxs"> <div class="rxleft"> 第一段内容,可以是任何html标签 </div> ...
- Spark Sort-Based Shuffle具体实现内幕和源码详解
为什么讲解Sorted-Based shuffle?2方面的原因:一,可能有些朋友看到Sorted-Based Shuffle的时候,会有一个误解,认为Spark基于Sorted-Based Shuf ...
- Hadoop集群安装-CDH5(5台服务器集群)
CDH5包下载:http://archive.cloudera.com/cdh5/ 架构设计: 主机规划: IP Host 部署模块 进程 192.168.254.151 Hadoop-NN-01 N ...
- linux文件系统软链接硬链接
引子 目前,UNIX的文件系统有很多种实现,例如UFS(基于BSD的UNIX文件系统).ext3.ext4.ZFS和Reiserfs等等. 不论哪一种文件系统,总是需要存储数据.硬盘的最小存储单位是扇 ...
- 【最大连接数】Linux的文件最大连接数
Too many open files ==================================== 查看当前操作系统连接数设置 ulimit -a =================== ...
- VS2010/MFC编程入门之三十九(文档、视图和框架:概述)
前面几节讲了菜单.工具栏和状态栏的使用,鸡啄米本节开始将为大家讲解文档.视图和框架的知识. 文档.视图和框架简介 在VS2010/MFC编程入门之三十四(菜单:VS2010菜单资源详解)创建的单文档工 ...