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

huangapple go评论75阅读模式
英文:

Gson custom serialization for fields with custom annotation

问题

<!-- language: java -->

class Demo {
  private String name;
  private int total;

  ...
}

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

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

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

<!-- language: java -->

class Demo {
  @Xyz
  private String name;

  private int total;

  ...
}

当我在类属性上使用这个注解时,序列化的数据应该符合以下格式:

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

请注意,无论类的类型如何,此注解都可以应用于任何(String)字段。如果我能在自定义的序列化器的 serialize 方法中获取特定字段的已声明注解,那对我来说将是有效的。

请指导如何实现这一点。

英文:

<!-- language: java -->

class Demo {
  private String name;
  private int total;

   ...
}

When I'm serializing an object of demo with gson, I'll get something like this in the normal scenario:

{&quot;name&quot;: &quot;hello world&quot;, &quot;total&quot;: 100}

Now, I have an annotation @Xyz which can be added to any attribute of any class. (The attribute to which I can apply this annotation can be anything, but for now it should be okay if it is just String type )

<!-- language: java -->

class Demo {
  @Xyz
  private String name;

  private int total;

  ...
}

When I've the annotation on the class attribute, the serialized data should be of the following format:

{&quot;name&quot;: {&quot;value&quot;: &quot;hello world&quot;, &quot;xyzEnabled&quot;: true}, &quot;total&quot;: 100}

Please note that this annotation can be applied to any (String) field regardless of the type of the class. If I could somehow get the declared annotations for that specific field on the custom serialiser serialize method, that would work for me.

Please advice how to achieve this.

答案1

得分: 6

I think you meant to use annotation JsonAdapter with your custom behaviour

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

import com.google.gson.*;

import java.lang.reflect.Type;

public class Xyz implements JsonSerializer&lt;String&gt;, JsonDeserializer&lt;String&gt; {

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

请注意,以上是你提供的代码的翻译部分,没有其他内容。

英文:

I think you meant to use annotation JsonAdapter with your custom behaviour

This is a sample class Xyz which extends JsonSerializer<String>, JsonDeserializer<String>

import com.google.gson.*;

import java.lang.reflect.Type;

public class Xyz implements JsonSerializer&lt;String&gt;, JsonDeserializer&lt;String&gt; {

  @Override
  public JsonElement serialize(String element, Type typeOfSrc, JsonSerializationContext context) {
    JsonObject object = new JsonObject();
    object.addProperty(&quot;value&quot;, element);
    object.addProperty(&quot;xyzEnabled&quot;, 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;
}

I've written some more tests maybe they'll help you to solve this problem more

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 = &quot;hello world&quot;;
    //when
    String json = new Gson().toJson(demo);
    //then
    assertEquals(&quot;{\&quot;name\&quot;:{\&quot;value\&quot;:\&quot;hello world\&quot;,\&quot;xyzEnabled\&quot;:true},\&quot;total\&quot;:100}&quot;, json);
  }

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

}

huangapple
  • 本文由 发表于 2020年4月7日 17:35:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/61076945.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定