如何将一个属性作为Map的值的列表序列化?我已经能够使用getter方法上的@JsonSerialize(using=...)
注解进行其他简单的转换。但是,我不确定是否有适用于我要做的操作的注解。
我们需要类似的东西,在我们的情况下,我们使用了一个定制的@JsonSerialize
,正如你所评论的,这很简单:
public class MyCustomSerializer extends JsonSerializer<Map<?, ?>> {
@Override
public void serialize(final Map<?, ?> value, final JsonGenerator jgen, final SerializerProvider provider)
throws IOException, JsonProcessingException {
jgen.writeObject(value.values());
}
}
使用它的代码:
import java.io.IOException;
import java.util.Collections;
import java.util.Map;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.JsonProcessingException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.JsonSerializer;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializerProvider;
import org.codehaus.jackson.map.annotate.JsonSerialize;
public class JacksonTest {
public static class ModelClass {
private final Map<String, String> map;
public ModelClass(final Map<String, String> map) {
super();
this.map = map;
}
@JsonSerialize(using = MyCustomSerializer.class)
public Map<String, String> getMap() {
return map;
}
}
public static void main(final String[] args) throws JsonGenerationException, JsonMappingException, IOException {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.writeValue(System.out, new ModelClass(Collections.singletonMap("test", "test")));
}
}
我使用默认序列化程序来处理不仅是字符串的值:
@Override
public void serialize(final Map<Long, ?> value, final JsonGenerator jgen, final SerializerProvider provider) throws IOException,
JsonProcessingException {
provider.defaultSerializeValue(value.values(), jgen);
}
编辑:正如Radu Simionescu所提到的,此解决方案仅适用于POJO的地图。