jsr367-experts@jsonb-spec.java.net

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

From: Dmitry Kornilov <dmitry.kornilov_at_oracle.com>
Date: Mon, 9 Nov 2015 00:26:31 +0100

Thanks for your answer. If similar methods exist in other frameworks (like Gson) users may want to have a similar functionality in the standard. So possibly it’s a good idea to keep them.

Dmitry

> On 06 Nov 2015, at 19:15, Inderjeet Singh <inder_at_alumni.stanford.edu> wrote:
>
> 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 <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 <mailto: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
>