JsonGenerator写入对象和字符串字段

时间:2015-10-28 13:22:45

标签: java json jackson

我正在尝试从对象生成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"
}

1 个答案:

答案 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