users@jsonb-spec.java.net

[jsonb-spec users] [jsr367-experts] Re: [30-GenericTypeSupport] Proposal

From: Eugen Cepoi <cepoi.eugen_at_gmail.com>
Date: Thu, 12 Mar 2015 17:51:22 +0100

Hey Martin,

2015-03-12 17:21 GMT+01:00 Martin Vojtek <voytoo_at_gmail.com>:

> Hi Experts,
>
> I would like to open discussion about Generic Type Support in JSON Binding.
>
> The initial proposal is to add two methods to Jsonb interface:
>
> public <T> T fromJson(String str, java.lang.reflect.Type runtimeType)
> throws JsonbException;
>
> public String toJson(Object object, java.lang.reflect.Type runtimeType)
> throws JsonbException;
>
> (and analogically other methods with different input/output)
>
> Based on reviewing existing options, it does not appear there is a single
> optimal option.
>
> Reasoning behind java.lang.reflect.Type.
>
> There are several ways how to deal with generics:
>
> 1. To use java.lang.reflect.Type
> 2. Use Type Literal (e.g. GenericType ...)
> 3. Use Generic Type Builder
>
> It would be a lot of unnecessary code to build Generic Type Builder. And I
> think this should be not part of JSON Binding.
>
>
I agree with you.


> Type Literal may work in some cases, but generally it doesn't work (in
> infinite cases). It is also not backed by Java Language Specification and
> may not work in the future. For example, Type Literal doesn't work when
> used with lambdas or with some JVM languages different than Java.
>

I understand but I think that it works in most use cases where it is
needed. People use it to just deal with basic generics (custom or std
types).


> I don't want to introduce yet another GenericType class and to duplicate
> code with some other specifications.
>

I agree it is ugly :( would have been better if there was a similar thing
as TypeToken from guava in std java (even if it is a hack in some way).


>
> Use of java.lang.reflect.Type seems like the best choice from bad choices
> available. Integration with JAX-RS will be flawless, it is upon the user to
> build java.lang.reflect.Type (hopefully with the help of JSON Binding
> implementation).
>
User can use already available Type Literal classes available in the Java
> ecosystem.
>

Good point and most people already use guava. Only downside will be the
untyped result of the fromJson.
Here we can avoid user cast by doing : <T> T fromJson(String, Type), but it
is definitely unsafe.

Might be interesting to have Inderjeets feedback on how it was when they
were using type and TypeToken.


>
> Examples and pdf proposal are available at
>
>
> https://java.net/projects/jsonb-spec/sources/git/content/spec/spec.pdf?rev=da7db533076856699cec49a4eebd300b9f4a7230
>
>
> https://github.com/json-binding/spec/blob/default_mapping/examples/runtime/src/main/java/examples/mapping/DefaultMappingGenerics.java
>
> Looking forward to your feedback.
>
> MartinV
>