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);
    }

 

posted @ 2022-06-02 15:28  yvioo  阅读(958)  评论(1编辑  收藏  举报