Java Gson具有自定义注释的字段的自定义序列化 类演示{ 私有字符串名称; 私人整数合计; ... }

Java Gson具有自定义注释的字段的自定义序列化 类演示{ 私有字符串名称; 私人整数合计; ... },java,spring,spring-boot,serialization,gson,Java,Spring,Spring Boot,Serialization,Gson,当我用gson序列化demo对象时,在正常情况下会得到如下结果: {“name”:“你好,世界”,“总计”:100} 现在,我有了一个注释@Xyz,它可以添加到任何类的任何属性中。(我可以应用这个注释的属性可以是任何东西,但是现在如果它只是Stringtype,就可以了) 类演示{ @Xyz 私有字符串名称; 私人整数合计; ... } 当我在class属性上添加注释时,序列化的数据应采用以下格式: {“name”:{“value”:“hello world”,“xyzEnabled”:tr

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

{“name”:“你好,世界”,“总计”:100}
现在,我有了一个注释
@Xyz
,它可以添加到任何类的任何属性中。(我可以应用这个注释的属性可以是任何东西,但是现在如果它只是
String
type,就可以了)

类演示{
@Xyz
私有字符串名称;
私人整数合计;
...
}
当我在class属性上添加注释时,序列化的数据应采用以下格式:

{“name”:{“value”:“hello world”,“xyzEnabled”:true},“total”:100}
请注意,无论类的类型如何,此注释都可以应用于任何(字符串)字段。如果我能在自定义serialiser
serialize
方法上以某种方式获得该特定字段的声明注释,那将对我有用


请给出如何实现这一点的建议。

我认为您的意思是在自定义行为中使用注释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();
  }
}
我已经写了更多的测试,也许它们会帮助你更好地解决这个问题

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

}

有什么问题吗?我的要求本身就是我的问题@123这是可行的,但问题是关于在字段上有自定义注释。
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);
  }

}