简体   繁体   中英

How to ignore certain fields for deserialization without jackson annotations?

I have a class inside a spring framework project. The class must not be annotated with jackson. But, it is annotated with @Component ie org.springframework.stereotype.Component.

Class

@Component
public class SampleClass{
    String prop1;
    String prop2;
    String prop3;
    //Getters & Setters.
}

Json

"SampleClassJson" : {
    String prop1;
    String prop2;
}

As you can see, SampleClassJson does not have prop3. I want to create a SampleClass object which does not have the prop3 field, by using jackson. I don't want to create another class just for one missing field. How do I achieve this ? I could not find any answers by using google or by looking at object mapper settings.

You have two options.

Use @JsonIgnore on getter or field

Sample class with @JsonIgnore annotation:

class Sample {
    private String prop1;
    private String prop2;
    @JsonIgnore // could be here
    private String prop3;

    @JsonIgnore // could be here
    public String getProp3() {
        return prop3;
    }
}

ObjectMapper use annotations from the Sample class:

new ObjectMapper().writeValueAsString(new Sample("one", "two", "three"))

Second variant, is to use custom serializer:

Custom serializer:

class SampleSerializer extends JsonSerializer<Sample> {

    @Override
    public void serialize(Sample sample, JsonGenerator jgen, SerializerProvider provider) throws IOException {
        jgen.writeStartObject();
        jgen.writeStringField("prop1", sample.getProp1());
        jgen.writeStringField("prop2", sample.getProp2());
        jgen.writeEndObject();
    }
}

Add annotation to use custom serializer:

@JsonSerialize(using = SampleSerializer.class)
class Sample {

    private String prop1;
    private String prop2;
    private String prop3;
}

ObjectMapper use annotations from the Sample class:

new ObjectMapper().writeValueAsString(new Sample("one", "two", "three"))

If you do not use Jackson annotations for the class at all, you could add your custom serializer to ObjectMapper :

Sample class does not contain any Jackson annotation:

class Sample {

    private String prop1;
    private String prop2;
    private String prop3;
}

ObjectMapper should know about the way how to serialize Sample class:

ObjectMapper mapper = new ObjectMapper();

SimpleModule module = new SimpleModule();
module.addSerializer(Sample.class, new SampleSerializer());
mapper.registerModule(module);

mapper.writeValueAsString(new Sample("one", "two", "three"));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM