jsonb-api
jsonb-api copied to clipboard
Support of TypeToken
Extend deserialize family with a method accepting TypeToken. It's more convenient and user friendly than using pure Type. Similar mechanism is used in Gson and Jackson.
Deserialization of generic list as it is now:
// List of dogs
List<Dog> dogs = new ArrayList<>();
// Initialization
...
// Create Jsonb and deserialize
Jsonb jsonb = JsonbBuilder.create();
dogs = jsonb.fromJson(result, new ArrayList<Dog>(){}.getClass().getGenericSuperclass());
Deserialization of generic list using TypeToken:
// List of dogs
List<Dog> dogs = new ArrayList<>();
// Initialization
...
// Create Jsonb and deserialize
Jsonb jsonb = JsonbBuilder.create();
dogs = jsonb.fromJson(result, TypeToken<List<Dog>>(){}.getType());
Links for the existing approaches mentioned in the OP:
GSON: https://static.javadoc.io/com.google.code.gson/gson/2.6.2/com/google/gson/reflect/TypeToken.html
Jackson: https://fasterxml.github.io/jackson-core/javadoc/2.2.0/com/fasterxml/jackson/core/type/TypeReference.html
Do you have the related discussion of the spec? Was rejected cause already too much duplicated accross the platform (see jaxrs and cdi to cite a few). Jakata.commons.next sounds a saner place IMHO.
If there were such discussions I didn't participate there. I agree that ideally it should be in JDK or in Common Annotations. On the other hand I don't think that other specs which use their own token solutions will switch to it.
Jaxrs and cdi would support it - cdi already btw, they didnt type anything with their typetoken and just used Type or Annotation as us. Jaxrs used it but can now move on so no need to just reinvent the wheel and let's either benefit from the donation or just stick to current option which works not that bad at all.
@rmannibucau I disagree that current option works not bad at all. Do you want to take an initiative and propose common platform level TypeToken to Jakarta EE Platform?
Maybe a compromise might be:
dogs = jsonb.fromJson(result, jsonb.createParameterizedType(List.class, Dog.class)); dogs = jsonb.fromJson(result, jsonb.createParameterizedType(Map.class, String.class, Dog.class)); dogs = jsonb.fromJson(result, jsonb.createParameterizedType(Map.class, String.class, jsonb.createParameterizedType(List.class, Animal.class)));