jackson中自定义处理序列化和反序列化
http://jackyrong.iteye.com/blog/2005323
**********************************************
对于一直用gson的人来说,如果单独用jackson,真是麻烦了,但还是得小结下了:
先来看下如何自定义把某个对象序列化为json:
先是对象:
Java代码
public class User {
public int id;
public String name;
}
public class Item {
public int id;
public String itemName;
public User owner;
}
JACKSON一般的使用很容易,如;
Item myItem = new Item(1, "theItem", new User(2, "theUser"));
String serialized = new ObjectMapper().writeValueAsString(myItem);
结果为:
{
"id": 1,
"itemName": "theItem",
"owner": {
"id": 2,
"name": "theUser"
}
}
如果要输出为如下的样子,比如;
{
"id": 25,
"itemName": "FEDUfRgS",
"owner": 15
}
则要自定义了,要继承JsonSerializer类,如下:
public class ItemSerializer extends JsonSerializer<Item> {
@Override
public void serialize(Item value, JsonGenerator jgen, SerializerProvider provider)
throws IOException, JsonProcessingException {
jgen.writeStartObject();
jgen.writeNumberField("id", value.id);
jgen.writeStringField("itemName", value.itemName);
jgen.writeNumberField("owner", value.owner.id);
jgen.writeEndObject();
}
}
然后
Item myItem = new Item(1, "theItem", new User(2, "theUser"));
ObjectMapper mapper = new ObjectMapper(); SimpleModule module = new SimpleModule();
module.addSerializer(Item.class, new ItemSerializer());
mapper.registerModule(module); String serialized = mapper.writeValueAsString(myItem);
看,相当复杂,然后看有无办法简单点,其实是有的哦;方法为:
@JsonSerialize(using = ItemSerializer.class)
public class Item {
...
}
就是使用注解@JsonSerialize,然后:
Item myItem = new Item(1, "theItem", new User(2, "theUser"));
String serialized = new ObjectMapper().writeValueAsString(myItem);
接下来看如何反序列化了,
同样,要反序列化的两个pojo为:
public class User {
public int id;
public String name;
}
public class Item {
public int id;
public String itemName;
public User owner;
}
反序列化代码为:
Item itemWithOwner = new ObjectMapper().readValue(json, Item.class);
如果要自定义反序列化,比如要反序列化的JSON为;
{
"id": 1,
"itemName": "theItem",
"owner": 2
}
则上面这样会报错:
com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException:
Unrecognized field "createdBy" (class org.baeldung.jackson.dtos.Item),
not marked as ignorable (3 known properties: "id", "owner", "itemName"])
at [Source: java.io.StringReader@53c7a917; line: 1, column: 43]
(through reference chain: org.baeldung.jackson.dtos.Item["createdBy"])
代码:
public class ItemDeserializer extends JsonDeserializer<Item> {
@Override
public Item deserialize(JsonParser jp, DeserializationContext ctxt)
throws IOException, JsonProcessingException {
JsonNode node = jp.getCodec().readTree(jp);
int id = (Integer) ((IntNode) node.get("id")).numberValue();
String itemName = node.get("itemName").asText();
int userId = (Integer) ((IntNode) node.get("id")).numberValue();
return new Item(id, itemName, new User(userId, null));
}
}
ObjectMapper mapper = new ObjectMapper();
SimpleModule module = new SimpleModule();
module.addDeserializer(Item.class, new ItemDeserializer());
mapper.registerModule(module);
Item readValue = mapper.readValue(json, Item.class);
也可以用注解:
@JsonDeserialize(using = ItemDeserializer.class)
public class Item {
...
}
jackson中自定义处理序列化和反序列化的更多相关文章
- 在Spark中自定义Kryo序列化输入输出API(转)
原文链接:在Spark中自定义Kryo序列化输入输出API 在Spark中内置支持两种系列化格式:(1).Java serialization:(2).Kryo serialization.在默认情况 ...
- 【SpringBoot】 中时间类型 序列化、反序列化、格式处理
[SpringBoot] 中时间类型 序列化.反序列化.格式处理 Date yml全局配置 spring: jackson: time-zone: GMT+8 date-format: yyyy-MM ...
- Asp.net中Json的序列化和反序列化(一)
JSON是专门为浏览器中的网页上运行的JavaScript代码而设计的一种数据格式.在网站应用中使用JSON的场景越来越多,本文介绍ASP.NET中JSON的序列化和反序列化,主要对JSON的简单介绍 ...
- ASP.NET中JSON的序列化和反序列化
JSON是专门为浏览器中的网页上运行的JavaScript代码而设计的一种数据格式.在网站应用中使用JSON的场景越来越多,本文介绍 ASP.NET中JSON的序列化和反序列化,主要对JSON的简单介 ...
- ASP.NET 中JSON 的序列化和反序列化
JSON是专门为浏览器中的网页上运行的JavaScript代码而设计的一种数据格式.在网站应用中使用JSON的场景越来越多,本文介绍ASP.NET中JSON的序列化和反序列化,主要对JSON的简单介绍 ...
- Asp.Net中JSON的序列化和反序列化-----JavaScriptSerializer ,加上自己工作心得
在工作中和手机通信用到web服务和javascriptSerializer,返回json数据,供手机端调用,一开始返回的数据是一大堆,比如 [{"word_picture9":&q ...
- ASP.NET中JSON的序列化和反序列化(转)
JSON是专门为浏览器中的网页上运行的JavaScript代码而设计的一种数据格式.在网站应用中使用JSON的场景越来越多,本文介绍ASP.NET中JSON的序列化和反序列化,主要对JSON的简单介绍 ...
- [转]ASP.NET中JSON的序列化和反序列化
本文转自:http://www.cnblogs.com/zhaozhan/archive/2011/01/09/1931340.html JSON是专门为浏览器中的网页上运行的JavaScript代码 ...
- Scala中使用 Jackson API 进行JSON序列化和反序列化
1. 什么是 Json 序列化 和 反序列化 序列化 => 将 Java对象 转换成 json字符串反序列化 => 将 json字符串 转换成 Java对象 2. 依赖包 说明 < ...
随机推荐
- libev与libevent区别
摘自stackflow的回答,主要从架构上说明了二者的区别: As for design philosophy, libev was created to improve on some of the ...
- atime,mtime,ctime 的理解
Linux之atime,mtime,ctime from:http://blog.sina.com.cn/s/blog_5980699f0100zkgz.html 首先可以使用stat 命令来查询文件 ...
- Elasticsearch报警插件Watch安装以及使用
参考:http://blog.csdn.net/ptmozhu/article/details/52296958 http://corejava2008.iteye.com/blog/2214279 ...
- simhash进行文本查重 Simhash算法原理和网页查重应用
simhash进行文本查重http://blog.csdn.net/lgnlgn/article/details/6008498 Simhash算法原理和网页查重应用http://blog.jobbo ...
- idea上activiti插件的安装及使用
最近做的东西需要用到activiti,做个笔记 首先下载activti插件- actiBPM File - settings-plugins-Browse-Repositories 搜索 actiBP ...
- android开发资源
android仿微信 http://www.oschina.net/code/snippet_253900_33261
- thinkphp使用中遇到的问题
参数传递的问题: 在传递文件路径的参数时,因为路由模式把斜杠解析了,所以需要对参数进行encode,使用urlencode不行,后来尝试用base64_encode,解决问题:
- 认识LINQ的第一步---从查询表达式开始
学习和使用C#已经有2个月了,在这两个月的学习中,深刻体会到,C#这门语言还真不适合编程初学者学习,因为它是吸取了很多其他语言,不仅是面向对象,还包括函数式语言的很多特性,导致它变成特性大爆炸的语言. ...
- xtrabackup 源码安装
安装依赖包:这些依赖包必须要先安装好 # yum install cmake libaio-devel ncurses-devel bzip2-devel libxml2-devel libgcryp ...
- C++的字符串格式化库
这里向大家介绍一个C++的字符串格式化库,叫cpptempl,这个库支持对字符串格式的条件,循环,变量插入.看上去很不错,只不过其是基于boost库的. 下面是一个例子: 1 2 3 4 5 6 7 ...