jsonb-api icon indicating copy to clipboard operation
jsonb-api copied to clipboard

Support of TypeToken

Open m0mus opened this issue 6 years ago • 6 comments
trafficstars

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());

m0mus avatar Jul 23 '19 12:07 m0mus

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

aguibert avatar Aug 27 '19 16:08 aguibert

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.

rmannibucau avatar Aug 27 '19 16:08 rmannibucau

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.

m0mus avatar Aug 27 '19 17:08 m0mus

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 avatar Aug 27 '19 19:08 rmannibucau

@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?

m0mus avatar Aug 28 '19 10:08 m0mus

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)));

rmannibucau avatar May 07 '21 09:05 rmannibucau