8

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
7
  • what do you expect your json to look like? Commented Jun 18, 2014 at 8:28
  • just as the first code (var=data) an array of arrays Commented Jun 18, 2014 at 8:29
  • I need to return something like this: [["1","2"],["3","4"],["5","6"]]; Commented Jun 18, 2014 at 8:32
  • is there any way i can create that and return it as a response? im using handsontable handsontable.com/demo/understanding_reference.html Commented Jun 18, 2014 at 8:35
  • 1
    Do not use writeXXXField() to write array elements because array elements are not fields but simple values, use methods that output simple values like writeNumber() or writeString(). Commented Jun 18, 2014 at 8:38

2 Answers 2

10

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.

Sign up to request clarification or add additional context in comments.

Comments

2
    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...?

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.