简体   繁体   中英

how to create json array using jackson

I need to create a json response for a report. Something like this:

var data = [
  ["", "Kia", "Nissan", "Toyota", "Honda"],
  ["2008", 10, 11, 12, 13],
  ["2009", 20, 11, 14, 13],
  ["2010", 30, 15, 12, 13]
];

Im using jackson library and i create a JsonGenerator, this is the code i have:

String[] cols = new String[5]; //Number of report columns

JsonFactory jfactory = new JsonFactory();
JsonGenerator jGenerator = jfactory.createJsonGenerator(response.getOutputStream(),JsonEncoding.UTF8);
jGenerator.writeStartArray();

jGenerator.writeStartArray();
jGenerator.writeStringField(cols[0], "");
//until...
jGenerator.writeStringField(cols[4], "Honda");
jGenerator.writeEndArray();
jGenerator.writeStartArray();
jGenerator.writeStringField(cols[0], "2008");
//until...
jGenerator.writeStringField(cols[4], "13");
jGenerator.writeEndArray();
//and the same with the next rows...

jGenerator.writeEndArray();

The problem is when setting the first value i get this error:

org.codehaus.jackson.JsonGenerationException: Can not write a field name, expecting a value

Can you build the array as an object before writing it, rather than bothering with all the individual pieces?

ObjectMapper mapper = new ObjectMapper();
ArrayNode array = mapper.createArrayNode();

int i = 0;
while (i < 6) {
    array.add(mapper.createArrayNode().add("" + i++).add("" + i++));
}
System.out.println(array);

Results in:

[["0","1"],["2","3"],["4","5"]]

If you're not dealing with several megabytes of data or very tight memory constraints, this might turn out to be more maintainable as well.

    JsonGenerator jg = new JsonFactory().createJsonGenerator(System.out);
    jg.configure(JsonGenerator.Feature.WRITE_NUMBERS_AS_STRINGS, true);
    jg.writeStartArray();
    int i = 0;
    while (i < 6)
    {
        jg.writeStartArray();
        jg.writeObject(i++);
        jg.writeObject(i++);
        jg.writeEndArray();
    }

    jg.writeEndArray();
    jg.flush();

OUTPUT:

 [["0","1"],["2","3"],["4","5"]]

Do you need a json like this...?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM