I have an object to serialize using Gson:
class User {
String firstname;
String lastname;
JsonElement opaqueData;
}
On the top object level, I want Gson to ignore null fields (say, if lastname is null, it should not be serialized).
But in field opaqueData , I want nulls to be serialized since it is supposed to a block of opaque data. So using new GsonBuilder().serializeNulls().create().toJson(user) would not work.
But @JsonAdapter does not work either
class User {
String firstname;
String lastname;
@JsonAdapter(NullAdapter.class)
JsonElement opaqueData;
}
class NullAdapter extends TypeAdapter<JsonElement> {
@Override
public void write(JsonWriter out, JsonElement value) throws IOException {
out.jsonValue(new GsonBuilder().serializeNulls().create().toJson(value));
}
@Override
public JsonElement read(JsonReader in) throws IOException {
// TODO Auto-generated method stub
return null;
}
}
It appears that the adapter is ignored by Gson.
Is this expected behavior? How can make this happen without create an adapter for the whole User class then manually serialize each field?