Gson使用@JsonAdapter自定义序列化简单demo
<dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> </dependency>
自定义序列化配置
DemoJsonAdapter.java
import com.google.gson.*; import com.google.gson.reflect.TypeToken; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import java.io.IOException; public enum DemoJsonAdapter implements TypeAdapterFactory { INSTANCE; @Override public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) { final TypeAdapter<JsonObject> jsonAdapter = gson.getAdapter(JsonObject.class); return new TypeAdapter<T>() { /** * 序列化过程 * @param out * @param value json内容 * @throws IOException */ @Override public void write(JsonWriter out, T value) throws IOException { TypeAdapter<T> delegateAdapter = (TypeAdapter<T>) gson.getDelegateAdapter(DemoJsonAdapter.INSTANCE, TypeToken.get(value.getClass())); //获取json内容 JsonObject tree = delegateAdapter.toJsonTree(value).getAsJsonObject(); //给json内容增加一个属性 tree.addProperty("self", "now"); //返回出去,没有这个将不会返回 jsonAdapter.write(out, tree); } /** * 反序列化 * @param in * @return * @throws IOException */ @Override public T read(JsonReader in) throws IOException { //获取的json JsonObject json = jsonAdapter.read(in); //去掉name属性 json.remove("name"); TypeAdapter<T> delegate = gson.getDelegateAdapter(DemoJsonAdapter.INSTANCE, type); return delegate.fromJsonTree(json); } }; } }
序列化的实体对象
DemoEntity.class
import com.example.demo.json.DemoJsonAdapter; import com.google.gson.annotations.JsonAdapter; import lombok.Data; import lombok.experimental.Accessors; @Data @Accessors(chain = true) @JsonAdapter(DemoJsonAdapter.class) public class DemoEntity { private Integer id; private String name; private Boolean bool; }
测试
public static void main(String []args) { DemoEntity entity=new DemoEntity(); entity.setId(1) .setName("name") .setBool(false); Gson gson=new Gson(); String toJson = gson.toJson(entity); System.out.println(toJson); DemoEntity fromJson = gson.fromJson(toJson, DemoEntity.class); System.out.println(fromJson); }
-----------------------有任何问题可以在评论区评论,也可以私信我,我看到的话会进行回复,欢迎大家指教------------------------
(蓝奏云官网有些地址失效了,需要把请求地址lanzous改成lanzoux才可以)