简体   繁体   English

Jackson JsonGenerator将子对象插入为JSON文字

[英]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.

相关问题 如何使用 Jackson JsonGenerator 将列表添加到 JSON - how to add a List to JSON using Jackson JsonGenerator JSONGenerator 如何在 JSON 中输出一个对象 - JSONGenerator How to output an object in the JSON 如何通过 jackson JsonGenerator 内联 object? - How inline object via jackson JsonGenerator? 你如何通过Jackson的JsonGenerator编写原始JSON? - How can you write raw JSON through Jackson's JsonGenerator? 杰克逊错误:没有这样的方法com.fasterxml.jackson.core.JsonGenerator.setCurrentValue(Ljava / lang / Object;)V - Jackson Error : No such method com.fasterxml.jackson.core.JsonGenerator.setCurrentValue(Ljava/lang/Object;)V 如何在杰克逊中映射子对象输入json? - How map Child Object input json in jackson? Java Jackson JsonGenerator:创建包装器 JSON 以在 java.lang.IllegalStateException 中列出结果:未定义 ObjectCodec - Java Jackson JsonGenerator: Creating wrapper JSON to list results in java.lang.IllegalStateException: No ObjectCodec defined 将JSON子对象属性绑定到Jackson中的Java对象字段 - Binding JSON child object property into Java object field in Jackson 如何为像javascript对象文字这样的json对象编写Jackson pojo类 - How to write a Jackson pojo class for a json object like a javascript object literal Jackson ObjectMapper和JsonGenerator-线程安全吗? - Jackson ObjectMapper & JsonGenerator - is it thread-safe?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM