1 回答
![?](http://img1.sycdn.imooc.com/54584e2c00010a2c02200220-100-100.jpg)
TA贡献1934条经验 获得超2个赞
米辛
在这种情况下,我们需要使用功能。创建如下界面:MixIn
interface WrapperModelMixIn {
@JsonSerialize(using = PropertyListJSONSerializer.class)
List<Property> getProperties();
}
并按如下方式注册:
ObjectMapper mapper = new ObjectMapper();
mapper.addMixInAnnotations(WrapperModel.class, WrapperModelMixIn.class);
较旧的提案
您需要使用允许为泛型类型注册序列化器的类型。更改后的序列化程序可能如下所示:Jackson
class PropertyListJSONSerializer extends StdSerializer<List<Property>> {
public PropertyListJSONSerializer(JavaType type) {
super(type);
}
@Override
public void serialize(List<Property> value, JsonGenerator gen, SerializerProvider provider)
throws IOException {
gen.writeStartObject();
for (Property p : value) {
gen.writeStringField(p.getName(), p.getValue());
}
gen.writeEndObject();
}
}
您可以按如下方式注册:
ObjectMapper mapper = new ObjectMapper();
CollectionType propertiesListType = mapper.getTypeFactory().constructCollectionType(List.class, Property.class);
SimpleModule module = new SimpleModule();
module.addSerializer(new PropertyListJSONSerializer(propertiesListType));
mapper.registerModule(module);
添加回答
举报