Gson序列化对象如何忽略字段
Gson序列化对象如何忽略字段
Gson版本 2.8.2
附gson-2.8.2下载链接
梗概
- 忽略字段。用注解
@Expose(serialize = false, deserialize = false)在类的成员上以告诉Gson 跳过本字段的(反)序列化。 (反)序列化时,需要Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create()而不是Gson gson = new Gson() - 自定义序列化和反序列化
忽略字段
比如有下User类,我不想把nickName也输出出来,网上查了查,说只要把注解改成@Expose(serialize = false, deserialize = false)
package go.Gson;
import com.google.gson.Gson;
import com.google.gson.annotations.Expose;
public class User {
User(String name_, String nickName_) {
name = name_;
nickName = nickName_;
}
public static void main(String[] args) {
User u = new User("Jackey", "Jack");
Gson gson = new Gson();
System.out.println(gson.toJson(u));//{"name":"Jackey","nickName":"Jack"}
}
@Expose
String name;
@Expose(serialize = false, deserialize = false)
String nickName;
}
事实是注解改了以后, 也还是会输出nickName的。
查看了下Gson-2.8.2的源码,在Expose.java中有注释,说如何使用
public class User {
@Expose private String firstName;
@Expose(serialize = false) private String lastName;
@Expose (serialize = false, deserialize = false) private String emailAddress;
private String password;
}
If you created Gson with {@code new Gson()}, the {@code toJson()} and {@code fromJson()}
methods will use the {@code password} field along-with {@code firstName}, {@code lastName},
and {@code emailAddress} for serialization and deserialization. However, if you created Gson
with {@code Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create()}
then the {@code toJson()} and {@code fromJson()} methods of Gson will exclude the
{@code password} field. This is because the {@code password} field is not marked with the
{@code @Expose} annotation. Gson will also exclude {@code lastName} and {@code emailAddress}
from serialization since {@code serialize} is set to {@code false}. Similarly, Gson will
exclude {@code emailAddress} from deserialization since {@code deserialize} is set to false.
即使用Gson gson = new Gson()注解不会生效,需要用Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create()去配置Gson
代码改成如下即可
package go.Gson;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.annotations.Expose;
public class User {
User(String name_, String nickName_) {
name = name_;
nickName = nickName_;
}
public static void main(String[] args) {
User u = new User("Jackey", "Jack");
Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
System.out.println(gson.toJson(u));// {"name":"Jackey"}
}
@Expose
String name;
@Expose(serialize = false, deserialize = false)
String nickName;
}
自定义序列化过程
设想一个UserWrapper类
package go.Gson;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.annotations.Expose;
public class UserWrapper {
UserWrapper(){
user = new User("Jackey", "Jack");
}
public static void main(String[] args) {
UserWrapper u = new UserWrapper();
Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
System.out.println(gson.toJson(u));
}
@Expose
private User user;
}
class User {
User(String name_, String nickName_) {
name = name_;
nickName = nickName_;
}
@Expose
String name;
@Expose(serialize = false, deserialize = false)
String nickName;
}
这个会输出{"user":{"name":"Jackey"}},这很讨厌,我们想让User对象只输出name的值,要这么做:
package go.Gson;
import java.lang.reflect.Type;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import com.google.gson.annotations.Expose;
public class UserWrapper {
UserWrapper(){
user = new User("Jackey", "Jack");
}
public static void main(String[] args) {
UserWrapper u = new UserWrapper();
Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation()
.registerTypeAdapter(User.class, new UserAdapter()).create();
System.out.println(gson.toJson(u));
}
@Expose
private User user;
}
class User {
User(String name_, String nickName_) {
name = name_;
nickName = nickName_;
}
@Expose
String name;
@Expose(serialize = false, deserialize = false)
String nickName;
}
class UserAdapter implements JsonSerializer<User> {
@Override
public JsonElement serialize(User src, Type typeOfSrc, JsonSerializationContext context) {
return context.serialize(src.name);
}
}
类似的interface 还有JsonDeserializer,TypeAdapter
Gson序列化对象如何忽略字段的更多相关文章
- Gson序列化对象时排除字段
import com.google.gson.ExclusionStrategy; import com.google.gson.FieldAttributes; /** *Gson序列化对象排除属性 ...
- xml 和 json 序列化忽略字段
xml 和 json 序列化忽略字段: @JsonIgnore @XmlTransient
- 完全理解Gson(2):Gson序列化
通过调用 Gson API 可以把 Java 对象转换为 JSON 格式的字符串(项目主页).在这篇文章中,我们将会讲到如何通过 Gson 默认实现和自定义实现方式,将 Java 对象转换为 JSO ...
- c# XML序列化与反序列化 属性字段标识
序列化对象 public class People { [XmlAttribute("NAME")] public string Name { set; get; } [XmlAt ...
- Java 序列化 对象序列化和反序列化
Java 序列化 对象序列化和反序列化 @author ixenos 对象序列化是什么 1.对象序列化就是把一个对象的状态转化成一个字节流. 我们可以把这样的字节流存储为一个文件,作为对这个对象的复制 ...
- FastJson的忽略字段和格式日期用法
1.指定序列化顺序 缺省fastjson序列化一个java bean,是根据fieldName的字母序进行序列化的,你可以通过ordinal指定字段的顺序.这个特性需要1.1.42以上版本. pub ...
- DELPHI XE2 采用 JSON 的方式来序列化对象
DELPHI XE2 采用 JSON 的方式来序列化对象 以下代码测试通过.问题是里面的中文,在反序列化后是乱码. 1. 序列化对象为字符串,Subject 里面的中文看起来正常,仍然是中文: 2. ...
- Android使用HttpURLConnection通过POST方式发送java序列化对象
使用HttpURLConnection类不仅可以向WebService发送字符串,还可以发送序列化的java对象,实现Android手机和服务器之间的数据交互. Android端代码: public ...
- 序列化对象为xml字符串
/// <summary> /// 序列化对象为xml字符串 /// </summary> /// <param name="obj" ...
随机推荐
- Micropython TurnipBit 电子时钟 青少年编程入门
电子时钟是一个很常用但是制作非常简单的小玩具了,对于Micropython初学者来说,制作一个电子时钟是非常简单又容易检验自己学习成果的实验了.TurnipBit相比于其他开发板,制作电子时钟就更加简 ...
- Android TV 电视调试和遥控器事件监听
Android TV 真机调试 要进行Android TV开发免不了要进行真机调试. 1.确定电视盒子和开发机器在同一局域网中 2.打开电视盒子的adb允许调试开关 3.进入adb所在文件夹进行adb ...
- Spring Boot Actutaur + Telegraf + InFluxDB + Grafana 构建监控平台之应用数据分析
本节将引入完美的granafa仪表板,在上节的基础上,并提出自己的一些监控数据的总结和看法 你可以有一个类似于这个的Dashboard,会引入监控Zimbra协作 本节环境采用的是centos7系统, ...
- 关于无法下载android开发工具的解决方法
目前中国内地访问android网站需要FQ.不过这个网站http://www.androiddevtools.cn/提供了所有的和官网上一样的android开发工具和一些其他问题的解决方法.为andr ...
- RedissonLock分布式锁源码分析
最近碰到的一个问题,Java代码中写了一个定时器,分布式部署的时候,多台同时执行的话就会出现重复的数据,为了避免这种情况,之前是通过在配置文件里写上可以执行这段代码的IP,代码中判断如果跟这个IP相等 ...
- 用js制作日期 2017-03-23
日期表: <body> <select id="year" ></select>年 <select id="month" ...
- 深入浅出了解OCR识别票据原理(Applying OCR Technology for Receipt Recognition)
原文:Applying OCR Technology for Receipt Recognition 译文:深入浅出了解OCR识别票据原理 英文票据识别技术, 非中文票据识别技术, 中文情况的ocr更 ...
- 关闭NetworkManager的作用
author: headsen chen date: 2017-11-21 13:34:23 个人原创 重启网卡后,会造成网卡失效,报错如下: Bringing up interface eth0 ...
- NEO从入门到开窗(1) - 一个智能合约的诞生
一.啰嗦两句 最近一直都在研究区块链,BitCoin,Etherenum, Hyper Ledger Fabric还有今天的主角小蚂蚁,当然出名以后改了一个艺名叫NEO.区块链大部分都是用Golang ...
- ASCII代码
ASCII(American Standard Code for Information Interchange,美国标准信息交换代码)是基于拉丁字母的一套电脑编码系统,主要用于显示现代英语和其他西欧 ...