[英]Gson custom serialization for fields with custom annotation
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:当我用 gson 序列化演示的 object 时,在正常情况下我会得到这样的结果:
{"name": "hello world", "total": 100}
Now, I have an annotation @Xyz
which can be added to any attribute of any class.现在,我有一个注释
@Xyz
,它可以添加到任何 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 ) (我可以应用此注释的属性可以是任何东西,但现在如果它只是
String
类型应该没问题)
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:当我对 class 属性进行注释时,序列化数据应采用以下格式:
{"name": {"value": "hello world", "xyzEnabled": true}, "total": 100}
Please note that this annotation can be applied to any (String) field regardless of the type of the class.请注意,无论 class 的类型如何,此注释都可以应用于任何(字符串)字段。 If I could somehow get the declared annotations for that specific field on the custom serialiser
serialize
method, that would work for me.如果我能以某种方式在自定义序列化程序序列
serialize
方法上获得该特定字段的声明注释,那对我有用。
Please advice how to achieve this.请建议如何实现这一目标。
I think you meant to use annotation JsonAdapter with your custom behaviour我认为您打算将注释 JsonAdapter与您的自定义行为一起使用
This is a sample class Xyz which extends JsonSerializer, JsonDeserializer这是一个示例 class 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();
}
}
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 = "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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.