Code Master 88
Code Master 88

Reputation: 11

How to get the Enum value in serialised JSON from a Java object

I have a Gender enum (which I can't edit) which is used in a Java class. Now, when I need to Serialise the Java class to JSON, I want the value of the Enum as part of the JSON and not the Enum name. For example below in my enum, and when this enum is serialized, I want the value as {"gender":"Male"} I am using:

String underWritingJSONString = objectMapper.writeValueAsString(myObject);

public enum Gender {
    MALE("Male"),
    FEMALE("Female");

    Gender(String gender) { 
        this.name = gender;
    }
    private String name; 

    String toValue() {
        return name;
    }
}

expected result = {"gender":"Male"}

current result = {"gender":"MALE"}

Following is the sample class

  public class MyObject {

    @JSONField
    public Gender gender;

    public MyObject() {

    }


    public Gender getGender() {
        return this.gender;
   }
}

Upvotes: 1

Views: 1776

Answers (3)

mallikarjun
mallikarjun

Reputation: 1862

If enum has toString() method which returns the value then

mapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING);

Is enough. But your enum don't have that as @Dinesh Kondapaneni mentioned you shold write a custom serializer like

class GenderSerializer extends JsonSerializer<Gender> {

@Override
public void serialize(Gender value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
    if (null == value) {
    } else {
        try {
            gen.writeString(value.toValue());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
        }
    }
}

}

And use it in your MyObject as

@JsonSerialize(using = GenderSerializer.class)
public Gender gender;

FYI: Am using jackson here

Upvotes: 1

Dinesh K
Dinesh K

Reputation: 299

(Jackson 2.6.2 and above) you can now simply write:

public enum Gender {
 @JsonProperty("Male")
 MALE,
 @JsonProperty("Female")
 FEMALE
  }

Upvotes: 0

Mushif Ali Nawaz
Mushif Ali Nawaz

Reputation: 3866

You need to add a method with annotation @JsonValue:

enum Gender {
    MALE("Male"),
    FEMALE("Female");

    Gender(String gender) { // constructor
        this.name = gender;
    }
    private String name; // variable

    @JsonValue
    String toValue() {
        return name;
    }
}

This method will be called when you are serializing your object to JSON.

Upvotes: 1

Related Questions