我正在尝试从对象生成JSON字符串并在同一级别添加字段。
{
"objField1": "objValue1",
"objField2": "objValue2",
"stringField": "stringValue"
}
以下是代码段:
PrintWriter writer = response.getWriter();
ObjectMapper mapper = new ObjectMapper();
JsonGenerator generator = mapper.getJsonFactory().createJsonGenerator(writer).useDefaultPrettyPrinter();
// mapper.writeValue(generator, responseObj); // tried this without success instead of the following
generator.writeObject(obj);
generator.writeStringField("stringField", "stringValue");
generator.close();
writer.close();
但我得到的只是我对象的字段:
{
"objField1": "objValue1",
"objField2": "objValue2"
}
答案 0 :(得分:2)
public void serialize(Object bean, JsonGenerator jgen,
SerializerProvider provider) throws IOException,
JsonGenerationException {
jgen.writeStartObject();
serializeFields(bean, jgen, provider);
jgen.writeStringField("extraField", "extraFieldValue");
jgen.writeEndObject();
}
看看这个链接: Jackson: How to add custom property to the JSON without modifying the POJO