-
Notifications
You must be signed in to change notification settings - Fork 4.4k
Closed
Labels
Description
Gson version
2.10.1
Java / Android version
Java 17
Used tools
- Maven; version: 3.8.1
Description
When a class has a field with :
- @SerializedName annotation with alternate names
- and with @JsonAdapter indicating a JsonSerializer class to use
Then a new JsonSerializer will instanciate for each alternate names, even if they will never be used (serialize is always false because of this)
Expected behavior
Instanciante a new JsonSerializer only for the main name, because created one can be an heavy operation.
Actual behavior
A new JsonSerializer will instanciate for each alternate names
Reproduction steps
Run the following code
public static class Pojo {
@SerializedName(value = "field1", alternate = {"field2", "field3"})
@JsonAdapter(StringSerializer.class)
public final String str;
public Pojo(String str) {
this.str = str;
}
}
public static class StringSerializer implements JsonSerializer<String> {
private static int count = 0;
private final int c;
public StringSerializer() {
this.c = count;
System.out.println("new StringSerializer " + this.c);
count++;
}
@Override
public JsonElement serialize(String value, Type type, JsonSerializationContext context) {
System.out.println("serialize " + this.c);
return new JsonPrimitive(value);
}
}
public static void main(String[] args) {
TypeAdapter<Pojo> adapter = new Gson().getAdapter(Pojo.class);
Pojo pojo1 = new Pojo("my value 1");
Pojo pojo2 = new Pojo("my value 2");
adapter.toJson(pojo1);
adapter.toJson(pojo2);
}
Dev hint
Maybe we can give serialize
value to this method call and used it in some way ?
OR