杰克逊没有产生预期的杰森

时间:2014-09-16 05:42:06

标签: java json jackson

我正在使用fastxml jackson apis生成json字符串:

"head" : { label : "head", data : [[2001,5678],[2002,6127]] }

但是,生成下面的字符串时没有逗号和额外的冒号和大括号:

{"head":{"label":"head","data":{:[{:2001:5678}]:[{:2002:6127}]}}}

代码:

JsonFactory jfactory = new JsonFactory();

StringWriter writer = new StringWriter();
JsonGenerator jGenerator = jfactory.createGenerator(writer);

jGenerator.writeStartObject();

jGenerator.writeObjectFieldStart("head");
jGenerator.writeStringField("label", "head");

jGenerator.writeObjectFieldStart("data");

jGenerator.writeStartArray();
jGenerator.writeStartObject();

jGenerator.writeNumber(2001);
jGenerator.writeNumber(5678);

jGenerator.writeEndObject();
jGenerator.writeEndArray();

jGenerator.writeStartArray();
jGenerator.writeStartObject();

jGenerator.writeNumber(2002);
jGenerator.writeNumber(6127);

jGenerator.writeEndObject();
jGenerator.writeEndArray();

jGenerator.writeEndObject();
jGenerator.writeEndObject();

jGenerator.close();

LOGGER.info(writer.toString());

1 个答案:

答案 0 :(得分:0)

JsonGenerator是用于编写JSON值的工具。它将在适当的上下文中编写您要写的任何内容。

jGenerator.writeStartObject(); // {

jGenerator.writeObjectFieldStart("head"); // {"head": {
jGenerator.writeStringField("label", "head"); // {"head": {"label":"head"

jGenerator.writeObjectFieldStart("data"); // {"head": {"label":"head", "data": {

// you're in the context of an object, so a name is expected, it will be empty when written
jGenerator.writeStartArray(); // {"head": {"label":"head", "data": {:[
jGenerator.writeStartObject(); // {"head": {"label":"head", "data": {:[{
// again, you're in the context of an object, so a name is expected
jGenerator.writeNumber(2001); // {"head": {"label":"head", "data": {:[{:2001

鉴于您的预期结果,这

jGenerator.writeObjectFieldStart("data"); // {"head": {"label":"head", "data": {

实际上应该是一个数组字段开始

jGenerator.writeArrayFieldStart("data"); // {"head": {"label":"head", "data": [

然后你不应该写对象的开始,只是数组。