有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java Gson对带有自定义注释的字段进行自定义序列化

class Demo {
  private String name;
  private int total;

   ...
}

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

{"name": "hello world", "total": 100}

现在,我有了一个注释@Xyz,它可以添加到任何类的任何属性中。(我可以应用这个注释的属性可以是任何东西,但是现在,如果它只是String类型,就可以了)

class Demo {
  @Xyz
  private String name;

  private int total;

  ...
}

当我在class属性上添加注释时,序列化的数据应该是以下格式:

{"name": {"value": "hello world", "xyzEnabled": true}, "total": 100}

请注意,无论类的类型如何,此注释都可以应用于任何(字符串)字段。如果我能在自定义serialiserserialize方法上获得该特定字段的声明注释,那对我来说就行了

请建议如何实现这一点


共 (1) 个答案

  1. # 1 楼答案

    我想你是想在你的习惯行为中使用注释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.annotations.JsonAdapter;
    
    public class Demo {
      @JsonAdapter(Xyz.class)
      public String name;
      public int total;
    }
    

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

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