假设我有以下结构:
public class SomeClass {
private String id;
@JsonProperty("key-value")
private Map<String, Object> keyValue;}
显然,它将被序列化为
{
"id" : "id1",
"key-value" :
{"key1" : "value1",
"key2 : "value2"}
}
是否有可能像这样代表它?
{
"id" : "id1",
"key1" : "value1",
"key2 : "value2"
}
提前致谢!
答案 0 :(得分:1)
在Jackson的自定义序列化器的帮助下很有可能:
@JsonSerialize
annoation添加到您的POJO:(还添加了必要的ctor和getters)
@JsonSerialize(using = SomeClassSerializer.class)
public static class SomeClass {
private String id;
@JsonProperty("key-value")
private Map<String, Object> keyValue;
public SomeClass(String id, Map<String, Object> keyValue) {
this.id = id;
this.keyValue = keyValue;
}
public String getId() { return id; }
public Map<String, Object> getKeyValue() { return keyValue; }
}
public class SomeClassSerializer extends JsonSerializer<SomeClass>
{
@Override
public void serialize(SomeClass sc, JsonGenerator gen, SerializerProvider serializers)
throws IOException, JsonProcessingException
{
gen.writeStartObject();
// write id propertry
gen.writeStringField("id", sc.getId());
// loop on keyValue entries, write each as property
for (Map.Entry<String, Object> keyValueEntry : sc.getKeyValue().entrySet()) {
gen.writeObjectField(keyValueEntry.getKey(), keyValueEntry.getValue());
}
gen.writeEndObject();
}
}
public static void main(String[] args)
{
Map<String, Object> keyValue = new HashMap<>();
keyValue.put("key1", "value1");
keyValue.put("key2", "value2");
keyValue.put("key3", new Integer(10));
SomeClass sc = new SomeClass("id1", keyValue);
try {
new ObjectMapper().writeValue(System.out, sc);
} catch (IOException e) {
e.printStackTrace();
}
}
输出:
{"id":"id1","key1":"value1","key2":"value2","key3":10}