[英]Jackson JsonGenerator insert child object as JSON literal
I'm generating JSON using Jackson's JsonGenerator, and would like to insert a child object from a literal JSON string. 我正在使用Jackson的JsonGenerator生成JSON,并想从文字JSON字符串中插入一个子对象。
gen.writeStartObject();
gen.writeStringField("name", "john");
gen.writeFieldName("profile");
gen.writeRaw(profilestring);
gen.writeEndObject();
This results in 这导致
Could not write content: Can not write a field name, expecting a value; nested exception is com.fasterxml.jackson.core.JsonGenerationException: Can not write a field name, expecting a value
Any thoughts? 有什么想法吗?
Update: solved using 更新:使用解决
gen.writeRaw(",\"profile\":" + profilestring);
Use writeRawValue rather than writeRaw to make the generator output the right punctuation and update its state (tested with 2.5.3): 使用writeRawValue而不是writeRaw来使生成器输出正确的标点符号并更新其状态(已通过2.5.3测试):
@Test
public void write_raw() throws Exception {
StringWriter sw = new StringWriter();
String profileString = "{\"foo\":true}";
try (JsonGenerator gen = mapper.getFactory().createGenerator(sw)) {
gen.writeStartObject();
gen.writeStringField("name", "john");
gen.writeFieldName("profile");
gen.writeRawValue(profileString);
gen.writeEndObject();
}
assertThat(sw.toString(), equivalentTo("{name:'john',profile:{foo:true}}"));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.