1

Using GSON is if it is possible to specify multiple JsonSerializers for a single object to allow for different data to be exposed with it programmatically?

For example I have this POJO

public class Person {

    private Long id;

    private String name;

    private String email;

    private Set<Addresses> addresses;
}

and this corresponding JsonSerializer:

public static final JsonSerializer<Person> serializer1 =
(Person src, java.lang.reflect.Type typeOfSrc, JsonSerializationContext context) -> {
    JsonObject personJson = new JsonObject();
    personJson.addProperty("name", src.getName());
    personJson.addProperty("email", src.getEmail());

    return personJson;
}

Now is it possible for me to add a second JsonSerializer like this to expose alternative data? Also if so how would you tell Gson to differentiate between the 2?

public static final JsonSerializer<Person> serializer2 =
(Person src, java.lang.reflect.Type typeOfSrc, JsonSerializationContext context) -> {
    JsonObject personJson = new JsonObject();
    personJson.addProperty("name", src.getName());
    personJson.addProperty("email", src.getEmail());

    personJson.add("addresses", toJsonArray(src.getAddresses()))

    return personJson;
}
AADJ
  • 65
  • 1
  • 8
  • 1
    You can build many instances of `Gson` object using `GsonBuilder` and it's [registerTypeAdapter](https://javadoc.io/doc/com.google.code.gson/gson/latest/com.google.gson/com/google/gson/GsonBuilder.html) method. For example take a look at [Correct Date format to use for GsonBuilder Date Format](https://stackoverflow.com/questions/58999880/correct-date-format-to-use-for-gsonbuilder-date-format/59041152#59041152) or [Converting Integer value to ...](https://stackoverflow.com/questions/55091868/gson-converting-integer-value-to-boolean-value-dynamically-for-specific-fields/55092786#55092786) – Michał Ziober Jan 22 '20 at 11:47

0 Answers0