Gson序列化对象如何忽略字段

Gson版本 2.8.2

附gson-2.8.2下载链接

gson-2.8.2-sources.jar

gson-2.8.2.jar

梗概

  • 忽略字段。用注解@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序列化对象如何忽略字段的更多相关文章

  1. Gson序列化对象时排除字段

    import com.google.gson.ExclusionStrategy; import com.google.gson.FieldAttributes; /** *Gson序列化对象排除属性 ...

  2. xml 和 json 序列化忽略字段

    xml 和 json 序列化忽略字段: @JsonIgnore @XmlTransient

  3. 完全理解Gson(2):Gson序列化

    通过调用 Gson API 可以把 Java 对象转换为 JSON 格式的字符串(项目主页).在这篇文章中,我们将会讲到如何通过 Gson 默认实现和自定义实现方式,将 Java  对象转换为 JSO ...

  4. c# XML序列化与反序列化 属性字段标识

    序列化对象 public class People { [XmlAttribute("NAME")] public string Name { set; get; } [XmlAt ...

  5. Java 序列化 对象序列化和反序列化

    Java 序列化 对象序列化和反序列化 @author ixenos 对象序列化是什么 1.对象序列化就是把一个对象的状态转化成一个字节流. 我们可以把这样的字节流存储为一个文件,作为对这个对象的复制 ...

  6. FastJson的忽略字段和格式日期用法

     1.指定序列化顺序 缺省fastjson序列化一个java bean,是根据fieldName的字母序进行序列化的,你可以通过ordinal指定字段的顺序.这个特性需要1.1.42以上版本. pub ...

  7. DELPHI XE2 采用 JSON 的方式来序列化对象

    DELPHI XE2 采用 JSON 的方式来序列化对象 以下代码测试通过.问题是里面的中文,在反序列化后是乱码. 1. 序列化对象为字符串,Subject 里面的中文看起来正常,仍然是中文: 2.  ...

  8. Android使用HttpURLConnection通过POST方式发送java序列化对象

    使用HttpURLConnection类不仅可以向WebService发送字符串,还可以发送序列化的java对象,实现Android手机和服务器之间的数据交互. Android端代码: public ...

  9. 序列化对象为xml字符串

    /// <summary>    /// 序列化对象为xml字符串    /// </summary>    /// <param name="obj" ...

随机推荐

  1. 论文笔记(1):From Image-level to Pixel-level Labeling with Convolutional Networks

    文章采用了多实例学习(MIL)机制构建图像标签同像素语义的关联 . 该方法的训练样本包含了70 万张来自ImageNet的图片,但其语义分割的性能很大程度上依赖于复杂的后处理过程,主要包括图像级语义的 ...

  2. react-redux状态管理思想

    最近一段一直在加班做项目,几乎每天都要加班到晚上9点,每周也只休息一天,一直没有时间把eact全家桶,再整体熟悉一遍.索性,就在最近的项目中,借鉴了react-redux的思想,维护状态和发布acti ...

  3. 安装paramiko

    前记: 各种奇葩事情都让我遇上了... 1.准备: 1>需要安装python 2>需要安装PyCrypto 2.安装python---省略 3.安装PyCrypto 1>检查pyth ...

  4. Vuex 教程案例:计数器以及列表展示

    本案例github:https://github.com/axel10/Vuex_demo-Counter-and-list 本篇教程将以计数器及列表展示两个例子来讲解Vuex的简单用法. 从安装到启 ...

  5. Spring Boot会员管理系统——处理文件上传

    温馨提示 Spring Boot会员管理系统的中,需要涉及到Spring框架,SpringMVC框架,Hibernate框架,thymeleaf模板引擎.所以,可以学习下这些知识.当然,直接入门的话使 ...

  6. NYOJ 题目12喷水装置(二)

    #include<iostream> #include<algorithm> #include<cmath> using namespace std; struct ...

  7. 分享一个命令行计算器-bc

    分享一个命令行计算器-bc 假如你在一个图形桌面环境中需要一个计算器时,你可能只需要一路进行点击便可以找到一个计算器.例如,Fedora 工作站中就已经包含了一个名为 Calculator 的工具.它 ...

  8. 二分查找的变种(Java实现)

    普通二分查找: 先回顾一下普通的二分查找 注意:二分查找有这样一个问题:当数组中数有重复时,比如 {3,3,3,3} 这个数组,二分查找3时,返回的是arr[1],也就是说二分查找并不会返回3第一次出 ...

  9. 通向架构师的道路之 Tomcat 性能调优

    一.总结前一天的学习 从"第三天"的性能测试一节中,我们得知了决定性能测试的几个重要指标,它们是: 吞吐量 Responsetime Cpuload MemoryUsage 我们也 ...

  10. json字符串对象内嵌json对象

    有时候需要在json的key:value字符串对象中再嵌入一个json对象,如果需要把如下的json对象作为字符串嵌入到json字符串对象中: { "type": 2, " ...