Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jackson Yaml Type Info is wrong on serialization

Tags:

java

yaml

jackson

I am getting the following output when serializing an object to yml via Jackson:

---
commands:
  dev: !<foo.bar.baz.DevCommand>

However, what I want is:

---
commands:
  dev: 
    type: foo.bar.baz.DevCommand

I am able to deserialize that fine. That is to say, the deserialization part works as intended. I have put the following annotation everywhere I can think of:

@JsonTypeInfo(use=JsonTypeInfo.Id.CLASS, include=JsonTypeInfo.As.PROPERTY, property="type")

Including on the DevCommand interface, on DevCommand the concrete class, on the type which has the commands map (both the field and the getters/setters).

What do I need to do to force Jackson to use the type format I want?

like image 788
mtyson Avatar asked Oct 26 '16 21:10

mtyson


1 Answers

Yaml has type information built in already, so Jackson uses that by default. From this issue, the fix is to disable using the native type id.

YAML has native Type Ids and Object Ids, so by default those are used (assuming this is what users prefer). But you can disable this with:

YAMLGenerator.Feature.USE_NATIVE_TYPE_ID

and specifically disabling that; something like:

YAMLFactory f = new YAMLFactory();
f.disable(YAMLGenerator.Feature.USE_NATIVE_TYPE_ID);
ObjectMapper m = new ObjectMapper(f);

or, for convenience

YAMLMapper m = new YAMLMapper()
 disable(YAMLGenerator.Feature.USE_NATIVE_TYPE_ID);
like image 116
Michael Deardeuff Avatar answered Nov 10 '22 03:11

Michael Deardeuff