Gson序列化对象自定义

时间:2022-10-13 15:57:07

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