4

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?

htshame
  • 6,599
  • 5
  • 36
  • 56

2 Answers2

7

@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;
}

}

pL4Gu33
  • 2,045
  • 16
  • 38
1

I strongly advise you to use DTOs. See why in this answer.


Alternatively you could use @JsonView. From Jackson 2.9, you could use @JsonAlias, which works only for deserialization.

cassiomolin
  • 124,154
  • 35
  • 280
  • 359