使用Gson自定义序列化带有自定义注释字段

4
class Demo {
  private String name;
  private int total;

   ...
}

当我使用Gson序列化Demo对象时,在正常情况下会得到以下内容:

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

现在,我有一个注解@Xyz,可以添加到任何类的任何属性上。(我可以将此注解应用于任何属性,但目前只需将其应用于String类型即可)

class Demo {
  @Xyz
  private String name;

  private int total;

  ...
}

当我在类属性上有注释时,序列化的数据应该符合以下格式:
{"name": {"value": "hello world", "xyzEnabled": true}, "total": 100}

请注意,此注释可应用于任何(String)字段,无论类的类型如何。如果我能以某种方式获取自定义序列化程序上特定字段的声明注释,那对我来说就可以工作了。
请指导如何实现这一点。

有问题吗? - 123
我的需求本身就是我的问题 @123 - Vijith mv
1个回答

6

我认为您想使用注解JsonAdapter来实现自定义行为。

这是一个扩展了JsonSerializer、JsonDeserializer的示例类Xyz。

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

this is a sample use

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

}

1
这个可以运行,但问题是关于在字段上拥有自定义注释。 - brunodles

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接