如何通过jackson JsonGenerator进行内联对象?

时间:2017-09-29 07:52:57

标签: java json jackson jackson2

考虑例子:

import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerator;

import java.io.File;
import java.io.FileInputStream;

public class Exmaple {
    public static void main (String[] args) throws Exception {

        Object object = new Object() {
            private String id = "someId";
        };

        final JsonGenerator generator = new JsonFactory().createGenerator(System.out);
        generator.writeStartObject();
        generator.writeFieldName("data");
        generator.writeBinary(new FileInputStream(new File("D:\\!Temp\\elasticsearch\\pdf.pdf")), -1);
        generator.writeEndObject();
        generator.writeObject(object);
        generator.close();
    }
}

目标是在json流式传输期间添加object的所有字段。有了这个代码,我得到了:

{
  "data": "JVBERi0xLjMKJ="
} {
  "id": "someId",
}

如何告诉jackson不要从对象中写{}

已更新

exprescted结果是(例如data +来自java对象的所有键):

{
  "data": "JVBERi0xLjMKJ=",
  "id": "someId",
}

1 个答案:

答案 0 :(得分:0)

致电writeEndObject()后,请不要致电writeBinary它应该是这样的:

final JsonGenerator generator = new JsonFactory().createGenerator(System.out);
        generator.writeStartObject();
        generator.writeFieldName("data");
        generator.writeBinary(new FileInputStream(new File("D:\\!Temp\\elasticsearch\\pdf.pdf")), -1);
        generator.writeObject(object);
        generator.writeEndObject();
        generator.close();