gpt4 book ai didi

java - Jackson JsonGenerator 将子对象插入为 JSON 文本

转载 作者:行者123 更新时间:2023-12-01 11:26:09 25 4
gpt4 key购买 nike

我正在使用 Jackson 的 JsonGenerator 生成 JSON,并且希望从文本 JSON 字符串插入子对象。

gen.writeStartObject();
gen.writeStringField("name", "john");
gen.writeFieldName("profile");
gen.writeRaw(profilestring);
gen.writeEndObject();

这会导致

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

有什么想法吗?

更新:使用解决

gen.writeRaw(",\"profile\":" + profilestring);

最佳答案

使用 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}}"));
}

关于java - Jackson JsonGenerator 将子对象插入为 JSON 文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30798734/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com