Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to create json array using jackson

Tags:

java

json

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
like image 824
Victor Elizondo Avatar asked Jun 19 '26 05:06

Victor Elizondo


1 Answers

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.

like image 193
Chris Avatar answered Jun 20 '26 19:06

Chris



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!