Skip to content

JsonSerializers are constructed multiple times when associated with SerializedName with alternate names but only one is used #2438

@d-william

Description

@d-william

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

Create this type adapter before here

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions