Jackson JsonGenerator insert child object as JSON literal

1.9k Views Asked by At

I'm generating JSON using Jackson's JsonGenerator, and would like to insert a child object from a literal JSON string.

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);
1

There are 1 best solutions below

0
On

Use writeRawValue rather than writeRaw to make the generator output the right punctuation and update its state (tested with 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}}"));
}