The reason for (4) is the good old Java Type Erasure.
What you writing out is essentially `Map<?,?>`, as far as available
type information tells -- there is nothing that could tell otherwise.

So as general rule:

- Do not serialize generic values as root value, if possible.
    o but if you do, you MUST provide type information separately
    o or, sub-class generic type to make it non-generic

Like so:

// instead of using reflection, construct as `TypeReference`
final TypeReference<?> fooType = new TypeReference<Map<String, Foo>>() { };
// (or using `TypeFactory.constructMapType(...)`)

// important: since root value is generic, MUST provide extra info to avoid
// it being seen as `Map<?,?>`
String json = m.writerFor(fooType)
    .writeValueAsString(o);
// after which read succeeds:
System.out.println ("5) " + m.readValue(json, fooType));

Or, with a work-around involving sub-classing to get non-generic type:

    static class FooMap extends HashMap<String,Foo> { }

and you do NOT need to specify type for serialization because type
information is now available via super-type declaration (so it's in
class definition; runtime type is still type-erased but that does not
matter).

I hope this helps,

-+ Tatu +-


On Tue, Dec 13, 2016 at 11:53 AM, Lev Kuznetsov
<lev.v.kuznet...@gmail.com> wrote:
> Try the code I pasted without the getter, it won't serialize type
> information if the object is a value in a map I'm trying to serialize (and
> same as part of a collection). The output for the code I pasted above is
>
> 1) {"@class":"foo.Test$Bar","lol":"lol"}
>
> 2) .Bar
>
> 3) {f=.Bar}
>
> 4) {"f":{"lol":"lol"}}
>
> Exception in thread "main"
> com.fasterxml.jackson.databind.JsonMappingException: Unexpected token
> (END_OBJECT), expected FIELD_NAME: missing property '@class' that is to
> contain type id  (for class foo.Test$Foo)
>
>
> Where the first line is serialization of the object itself, the fourth line
> is serialization of a map mapping the string "f" to the same object, notice
> how "@class" property is missing, followed by exception where it cannot
> deserialize this json back into a map.
>
> --
> You received this message because you are subscribed to the Google Groups
> "jackson-user" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to jackson-user+unsubscr...@googlegroups.com.
> To post to this group, send email to jackson-user@googlegroups.com.
> For more options, visit https://groups.google.com/d/optout.

-- 
You received this message because you are subscribed to the Google Groups 
"jackson-user" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to jackson-user+unsubscr...@googlegroups.com.
To post to this group, send email to jackson-user@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to