users@jsonb-spec.java.net

[jsonb-spec users] [jsr367-experts] Re: Generics support on serialization

From: Inderjeet Singh <inder_at_alumni.stanford.edu>
Date: Fri, 6 Nov 2015 10:15:25 -0800

This is how we did it in Gson. In the hindsight though, I will remove the
extra type parameter from toJson().

The only situation where it makes sense is when you want to limit the
response to a base type. For example:
class Sub extends Base {
   int a;
}
toJson(object, Base.class) omits the field "a".

In practice, it is rare, and there or workarounds such as add a type
adapter for Sub that limits the response to Base. Here is an example of
such a type adapter:
https://github.com/google-gson/typeadapters/blob/master/common/src/main/java/RestrictSerializationToBaseClassFactory.java




On Fri, Nov 6, 2015 at 7:28 AM, <dmitry.kornilov_at_oracle.com> wrote:

> Hi Experts,
>
> I am working on JSON-B reference implementation at the moment and want
> to clarify one moment. We have three Jsonb::toJson(...) methods
> accepting Type parameter:
>
> String toJson(Object object, Type runtimeType) throws JsonbException;
> void toJson(Object object, Type runtimeType, Appendable appendable)
> throws JsonbException;
> void toJson(Object object, Type runtimeType, OutputStream stream)
> throws JsonbException;
>
> I am not convinced why these methods are needed. Raw type is enough for
> serialization. For deserialization this parameter is obviously
> required.
>
> There is an example in DefaultMappingGenerics class which covers this
> case (see below). It can be (and is) perfectly processed without
> knowing a generic type. So this is a bad sample.
>
> List<java.util.Optional<String>> expected =
> Arrays.asList(Optional.empty(), Optional.ofNullable("first"),
> Optional.of("second"));
> String json = jsonb.toJson(expected,
> DefaultMappingGenerics.class.getField("listOfOptionalStringField").getG
> enericType());
> assertEquals("[null,\"first\",\"second\"]",json);
>
> Is there any real world sample showing that toJson(Object object) is
> not enough and toJson(Object object, Type runtimeType) has to be used.
>
> Thanks,
> Dmitry Kornilov
>