Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rename fields in object with Jackson

Tags:

java

jackson

I have the JSON:

{"400" : "120Hz"} 

(actually, my JSON is a lot more complex, and, basically, huge)

I use Jackson to map data to the FrequencyDTO.

public class FrequencyDTO {

    @JsonProperty("400")
    private String frequency;

    public String getFreqiency() {
        return this.frequency;
    }

    public void setFrequency(String frequency) {
        this.frequency = frequency;
    }
}

After that, I need to send this DTO to front end, but I want it's fields to be human-readable, such as: {"frequency_value" : "120Hz"}.

The only thing that came to my mind is to create some kind of FrequencyFrontendDTO, e.g.:

public class FrequencyFrontendDTO {

    @JsonProperty("frequency_value")
    public String frequency;

    //getters and setters
}

and map it with FrequencyDTO.

Is there a cleaner way to do it?

like image 453
htshame Avatar asked Oct 19 '25 14:10

htshame


1 Answers

@JsonAlias deserialization all alias in the attribute. But serialization is only for given @JsonProperty

public FrequencyDTO() {

@JsonProperty("frequency_value")
@JsonAlias({"400"})
private String frequency;

public String getFreqiency() {
    return this.frequency;
}

public void setFrequency(String frequency) {
    this.frequency = frequency;
}

}

like image 169
pL4Gu33 Avatar answered Oct 21 '25 04:10

pL4Gu33



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!