2 回答

TA貢獻1831條經驗 獲得超10個贊
您不需要自定義序列化程序。您可以利用@JsonAnyGetter注釋生成包含所需輸出屬性的地圖。
下面的代碼采用上面的示例 pojo 并生成所需的 json 表示。
首先,您已使用 注釋所有 getter 方法,@JsonIgnore以便 jackson 在序列化期間忽略它們。將被調用的唯一方法是帶@JsonAnyGetter注釋的方法。
public class SimplePojo {
private String key ;
private String value ;
private int thing1 ;
private boolean thing2;
// tell jackson to ignore all getter methods (and public attributes as well)
@JsonIgnore
public String getKey() {
return key;
}
// produce a map that contains the desired properties in desired hierarchy
@JsonAnyGetter
public Map<String, ?> getForJson() {
Map<String, Object> map = new HashMap<>();
Map<String, Object> attrMap = new HashMap<>();
attrMap.put("value", value);
attrMap.put("thing1", thing1); // will autobox into Integer
attrMap.put("thing2", thing2); // will autobox into Boolean
map.put(key, attrMap);
return map;
}
}

TA貢獻1860條經驗 獲得超9個贊
您需要使用writeObjectFieldStart方法來寫入字段并JSON Object以相同的類型打開新的:
class SimplePojoJsonSerializer extends JsonSerializer<SimplePojo> {
@Override
public void serialize(SimplePojo value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
gen.writeStartObject();
gen.writeObjectFieldStart(value.getKey());
gen.writeStringField("value", value.getValue());
gen.writeNumberField("thing1", value.getThing1());
gen.writeBooleanField("thing2", value.isThing2());
gen.writeEndObject();
gen.writeEndObject();
}
}
添加回答
舉報