javajacksonjax-rsjersey-1.0

Not able to convert underscore case to camel case with Jackson


I have a DTO class which has a property like:

@JsonIgnoreProperties(ignoreUnknown = true)
public class WPPostResponse {
    @JsonProperty("featuredMedia")
    Long featured_media;

    public Long getFeatured_media() {
        return featured_media;
    }

    public void setFeatured_media(Long featured_media) {
        this.featured_media = featured_media;
    }
}

The input JSON has the key featured_media. I convert the JSON string to the object and then sends it to the client response as JSON. I want the final response JSON to have featuredMedia as the key. I am however getting null as the value. If I remove the JsonProperty, it gives the value, but the key is having underscore. How to fix this? Thanks.


Solution

  • Always respect the Java naming conventions in your Java code. Use annotations to deal with Json not respecting them.

    In this case, use JsonAlias

    Annotation that can be used to define one or more alternative names for a property, accepted during deserialization as alternative to the official name

    public class WPPostResponse {
        @JsonAlias("featured_media")
        Long featuredMedia;
    
        public Long getFeaturedMedia() {
            return featuredMedia;
        }
    
        public void setFeaturedMedia(Long featuredMedia) {
            this.featuredMedia = featuredMedia;
        }
    }