自定义枚举
package com.qingqing.live.bean.enums;
import com.google.common.collect.ImmutableList;
import java.util.List;
public enum MesosConstraint {
node_voip("node",ConstraintType.EQUALS,"voip"),
node_live("node",ConstraintType.EQUALS,"live");
String attribute;
ConstraintType type;
String value;
MesosConstraint(String attribute, ConstraintType type, String value){
this.attribute = attribute;
this.type = type;
this.value = value;
}
public List<String> toList(){
return ImmutableList.<String>builder()
.add(attribute)
.add(type.toString())
.add(value)
.build();
}
}
枚举类型的序列化:
public class ConstraintSerializer extends JsonSerializer<Constraint> {
@Override
public void serialize(Constraint value, JsonGenerator jgen, SerializerProvider provider) throws IOException {
Optional<Constraint> data = Optional.of(value);
if (data.isPresent()){
jgen.writeObject(data.get().toList());
} else {
jgen.writeString("");
}
}
}
枚举数组的序列化:
package com.qingqing.liverres.converter;
import com.google.common.base.Optional;
import com.qingqing.live.bean.enums.MesosConstraint;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.map.SerializerProvider;
import org.codehaus.jackson.map.TypeSerializer;
import org.codehaus.jackson.map.ser.std.ContainerSerializerBase;
import org.codehaus.jackson.map.ser.std.StdArraySerializers;
import java.io.IOException;
public class MesosConstraintArraySerializer extends StdArraySerializers.ArraySerializerBase<MesosConstraint[]> {
protected MesosConstraintArraySerializer() {
super(MesosConstraint[].class, null, null);
}
@Override
protected void serializeContents(MesosConstraint[] value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonGenerationException {
for (MesosConstraint constraint: value){
Optional<MesosConstraint> data = Optional.of(constraint);
if (data.isPresent()){
jgen.writeObject(data.get().toList());
} else {
jgen.writeString("");
}
}
}
@Override
public ContainerSerializerBase<?> _withValueTypeSerializer(TypeSerializer vts) {
return this;
}
}
使用的时候在get方法上添加上@JsonSerialize(using=MesosConstraintArraySerializer.class)就可以使用了