@class is added, although this is the default value.

Using Jackson (JSON / Object mapper), let's say I have the following interface and classes:

@JsonTypeInfo(defaultImpl = Duck.class, use = JsonTypeInfo.Id.CLASS)
public interface Animal {
}

public class Duck implements Animal {
    private String name;
    public String getName() { return name; }
    public void setName(String name) { this.name = name; }
}

public class Park {
    private Animal animal;
    public Animal getAnimal() { return animal; }
    public void setAnimal(Animal animal) { this.animal = animal; }
}

And I'm trying to read (deserialize) this piece of JSON:

{
    "animal": {
        "name": "Quacky"
    }
}

via:

Park park = objectMapper.readValue(json, Park.class);

It works! Even without type information (@class or @type) it can build Duck, because I defined defaultImplfor the interface Animal.

Now I expect the same behavior when I do it the other way around.

String json = objectMapper.writeValueAsString(park);

But instead, I get this JSON:

{
    "animal": {
        "@class": "com.example.Duck"
        "name": "Quacky"
    }
}

It doesn't seem to respect defaultImplduring serialization! I want the @class attribute to disappear from the output file. Does anyone know how I can tell Jackson not to add the "@class" attribute to mine Duck?

+3
source share
1 answer

, . ,

( ) , , , @JsonTypeInfo (, , ). , Animal :

@JsonTypeInfo (use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY, = "@class" )  class Animal {} (, , ).

?

  • ( )
  • " " - Java (, "org.codehaus.jackson.sample.Animal" )
  • (meta-) ; "@class" ( if: "@class" )
  • ( @JsonTypeResolver); (no @JsonTypeIdResolver)

, Duck.

@JsonTypeInfo(use = JsonTypeInfo.Id.NONE)
public class Duck implements Animal {
    private String name;
    public String getName() { return name; }
    public void setName(String name) { this.name = name; }
}

SimpleModule simpleModule = new SimpleModule("SimpleModule", new Version(1,0,0,null));
simpleModule.addSerializer(new JsonSerializer< Duck > {
    @Override
    public void serialize(Duck duck, JsonGenerator jgen,
            SerializerProvider provider) throws IOException,
            JsonProcessingException {
        jgen.writeStartObject();
        jgen.writeStringField("name", duck.getName());
        jgen.writeEndObject();
    }
});
mapper.registerModule(simpleModule);
+4

All Articles