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:
{"name": "hello world", "total": 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 )
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:
{"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. 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.
I think you meant to use annotation JsonAdapter with your custom behaviour
This is a sample class Xyz which extends 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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With