DongHoon  Kim
DongHoon Kim

Reputation: 386

How to configure jackson for convert Enum to JSON?

@AllArgsConstructor
@Getter    
public enum MemberType {
    INTERN("name_intern", 1),
    EMPLOYEE("name_employee", 10);

    private String name;
    private int workingMonth;
}

Here is my enum. I want to convert Enum class to JSON string with some constraint.

  1. I want to MemberType has no dependency with Jackson
  2. I want to convert MemberType.INTERN to {id:INTERN, name:"name_intern", workingMonth:10}.
  3. I have lots of Enums want to convert like above. And Their number of property is different each other.
  4. I want resolve this problem through just one global configuration.
  5. I don't want to use explicit java reflection.

Is there a solution that meets the above constraints?

Upvotes: 5

Views: 3200

Answers (2)

Hiroki Matsumoto
Hiroki Matsumoto

Reputation: 377

If you implement JsonSerializer,you can custom serialization.

An example is shown below.

@JsonComponent
public final class MediaTypeJsonComponent {
    public static class Serializer extends JsonSerializer<MemberType> {
        @Override
        public void serialize(MemberType value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
            gen.writeStartObject();
            gen.writeStringField("id", value.name());
            gen.writeNumberField("workingMonth", value.getWorkingMonth());
            gen.writeStringField("name", value.getName());
            gen.writeEndObject();
        }
    }
    //
    // If you need,write code.
    //public static class Deserializer extends JsonDeserializer<Customer> {
    //}
}

Another way is to implement JsonSerialize.

If you want more information, you should refer to:

Upvotes: 2

Dina Bogdan
Dina Bogdan

Reputation: 4738

You can use @JsonFormat annotation like this:

 @JsonFormat(shape=JsonFormat.Shape.OBJECT)
 public enum MemberType { ... }

or you can use @JsonValue annotation like this:

public enum MemberType {
        [...]

@JsonValue
public String getName() {
 return name;
}

}

or maybe a CustomSerializer for Enum, you can find more details here.

Upvotes: 6

Related Questions