具有自定义注释的字段的 Gson 自定义序列化

Vij*_* mv 4 java serialization spring gson spring-boot

class Demo {
  private String name;
  private int total;

   ...
}
Run Code Online (Sandbox Code Playgroud)

当我使用 gson 序列化 demo 的对象时,在正常情况下我会得到类似的结果:

{"name": "hello world", "total": 100}
Run Code Online (Sandbox Code Playgroud)

现在,我有一个注释@Xyz,可以添加到任何类的任何属性中。(我可以应用此注释的属性可以是任何东西,但现在如果只是Stringtype 应该没问题)

class Demo {
  @Xyz
  private String name;

  private int total;

  ...
}
Run Code Online (Sandbox Code Playgroud)

当我对类属性进行注释时,序列化数据应采用以下格式:

{"name": {"value": "hello world", "xyzEnabled": true}, "total": 100}
Run Code Online (Sandbox Code Playgroud)

请注意,无论类的类型如何,此注释都可以应用于任何(字符串)字段。如果我能够以某种方式获得自定义序列化器方法上该特定字段的声明注释serialize,那么这对我有用。

请建议如何实现这一目标。

小智 6

我认为您打算将注释 JsonAdapter与您的自定义行为一起使用

这是一个示例类 Xyz,它扩展了 JsonSerializer、JsonDeserializer

import com.google.gson.*;

import java.lang.reflect.Type;

public class Xyz implements JsonSerializer<String>, JsonDeserializer<String> {

  @Override
  public JsonElement serialize(String element, Type typeOfSrc, JsonSerializationContext context) {
    JsonObject object = new JsonObject();
    object.addProperty("value", element);
    object.addProperty("xyzEnabled", true);
    return object;
  }

  @Override
  public String deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
    return json.getAsString();
  }
}
Run Code Online (Sandbox Code Playgroud)

这是一个示例使用

import com.google.gson.annotations.JsonAdapter;

public class Demo {
  @JsonAdapter(Xyz.class)
  public String name;
  public int total;
}
Run Code Online (Sandbox Code Playgroud)

我写了一些更多的测试也许它们会帮助你更多地解决这个问题

import com.google.gson.Gson;
import org.junit.Test;

import static org.junit.Assert.assertEquals;

public class Custom {
  @Test
  public void serializeTest() {
    //given
    Demo demo = new Demo();
    demo.total = 100;
    demo.name = "hello world";
    //when
    String json = new Gson().toJson(demo);
    //then
    assertEquals("{\"name\":{\"value\":\"hello world\",\"xyzEnabled\":true},\"total\":100}", json);
  }

  @Test
  public void deserializeTest() {
    //given
    String json = "{  \"name\": \"hello world\",  \"total\": 100}";
    //when
    Demo demo = new Gson().fromJson(json, Demo.class);
    //then
    assertEquals("hello world", demo.name);
    assertEquals(100, demo.total);
  }

}
Run Code Online (Sandbox Code Playgroud)