Reputation: 386
@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.
MemberType.INTERN
to {id:INTERN, name:"name_intern", workingMonth:10}
.Is there a solution that meets the above constraints?
Upvotes: 5
Views: 3200
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
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