简体   繁体   中英

Using Jackson (ObjectMapper) how serialize object to json and ignore all fields except the ones I annotate as @JsonProperty?

UPDATE:

I was wrapping my object in another one during the response creation and that class didn't have any @JsonProperty annotations. Adding them to its getter methods made this work.

Original I am trying to ignore all fields except the few that the class wants to keep, but I am getting an empty object (it's ignoring everything). How do i do this?

Converting the object to json string:

//The marshaller
ObjectMapper marshaller = new ObjectMapper();

//Make it ignore all fields unless we specify them
marshaller.setVisibility(
    new VisibilityChecker.Std(
        JsonAutoDetect.Visibility.NONE,
        JsonAutoDetect.Visibility.NONE,
        JsonAutoDetect.Visibility.NONE,
        JsonAutoDetect.Visibility.NONE,
        JsonAutoDetect.Visibility.NONE
    )
);

//Allow empty objects
marshaller.configure( SerializationFeature.FAIL_ON_EMPTY_BEANS, false );

return marshaller.writeValueAsString( myObject );

The object:

public class MyObject
{
    private Integer id;
    private Event event;
    private String name;
    private String description;
    private Timestamp createdDate;

    public EventAction(...)
    {
        ...elided...
    }

    public Integer getId()
    {
        return id;
    }

    public void setId(Integer id)
    {
        this.id = id;
    }

    public Event getEvent()
    {
        return event;
    }

    public void setEvent(Event event)
    {
        this.event = event;
    }

    @JsonProperty
    public String getName()
    {
        return name;
    }

    public void setName(String name)
    {
        this.name = name;
    }

    @JsonProperty
    public String getDescription()
    {
        return description;
    }

    public void setDescription(String description)
    {
        this.description = description;
    }

    public Timestamp getCreatedDate()
    {
        return createdDate;
    }

    public void setCreatedDate(Timestamp createdDate)
    {
        this.createdDate = createdDate;
    }
}

Move your @JsonProperty to the property/field level and this should work.

Sample w/ tests to verify.

https://github.com/Flaw101/jackson-ignore-everything/tree/master

Edit,

Updated for deserialization tests too.

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