Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enums for Jackson's @JsonProperty

Let's say I have an enum:

public enum ParameterList {
    FREQUENCY_ID("500");
    ...
    lot's of different constants here
    ...

    private final String param;

    ParameterList(String param) {
        this.param = param;
    }

    @Override
    public String toString() {
        return param;
    }
}

And let's say I have a DTO with field:

private String frequency;

Let's say I have a JSON:

{"500" : "100Hz"}

I want to map this json to my dto, so DTO.frequency will have a value of json's "500" field (which will be "100Hz").

I understand that only constants must be used as attribute values, but is there some workaround to make the following work?

@JsonProperty(ParameterList.FREQUENCY_ID)
private String frequency;

(@JsonProperty is com.fasterxml.jackson.annotation.JsonProperty, version 2.8.0)

The idea is to minimize the code edits when the enum ParameterList.FREQUENCY_ID will be changed from "500", to some other value.

like image 517
htshame Avatar asked Dec 09 '25 06:12

htshame


1 Answers

You could try the following:

public enum ParameterList {

    FREQUENCY_ID(Constants.FREQUENCY_ID_VALUE);

    private final String value;

    ParameterList(String value) {
        this.value= value;
    }

    @Override
    public String toString() {
        return value;
    }

    public static class Constants {
        public static final String FREQUENCY_ID_VALUE = "500";
    }
}

Then use:

@JsonProperty(ParameterList.Constants.FREQUENCY_ID_VALUE)
private String frequency;
like image 87
cassiomolin Avatar answered Dec 11 '25 19:12

cassiomolin



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!