用Jackson序列化枚举 [英] Serializing enums with Jackson
问题描述
我在下面有一个Enum desrcibed:
I have an Enum desrcibed below:
public enum OrderType {
UNKNOWN(0, "Undefined"),
TYPEA(1, "Type A"),
TYPEB(2, "Type B"),
TYPEC(3, "Type C");
private Integer id;
private String name;
private WorkOrderType(Integer id, String name) {
this.id = id;
this.name = name;
}
//Setters, getters....
}
我使用我的控制器返回枚举数组( new OrderType [] {UNKNOWN,TYPEA,TYPEB,TYPEC};
),然后Spring将其序列化为以下内容json string:
I return enum array with my controller ( new OrderType[] {UNKNOWN,TYPEA,TYPEB,TYPEC};
), and Spring serializes it into the following json string:
["UNKNOWN", "TYPEA", "TYPEB", "TYPEC"]
迫使Jackson像POJO一样序列化枚举的最佳方法是什么?例如:
What is the best approach to force Jackson to serialize enums just like POJOs? E.g.:
[
{"id": 1, "name": "Undefined"},
{"id": 2, "name": "Type A"},
{"id": 3, "name": "Type B"},
{"id": 4, "name": "Type C"}
]
我玩过不同的注释但不能设法得到这样的结果。
I played with different annotations but couldn't manage to get such result.
推荐答案
最后我自己找到了解决方案。
Finally I found solution myself.
我必须用 @JsonSerialize(using = OrderTypeSerializer.class)
注释enum并实现自定义序列化器:
I had to annotate enum with @JsonSerialize(using = OrderTypeSerializer.class)
and implement custom serializer:
public class OrderTypeSerializer extends JsonSerializer<OrderType> {
@Override
public void serialize(OrderType value, JsonGenerator generator,
SerializerProvider provider) throws IOException,
JsonProcessingException {
generator.writeStartObject();
generator.writeFieldName("id");
generator.writeNumber(value.getId());
generator.writeFieldName("name");
generator.writeString(value.getName());
generator.writeEndObject();
}
}
这篇关于用Jackson序列化枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!