Saturday, 15 September 2012

java - how to create json array using jackson -



java - how to create json array using jackson -

i need create json response report. this:

var info = [ ["", "kia", "nissan", "toyota", "honda"], ["2008", 10, 11, 12, 13], ["2009", 20, 11, 14, 13], ["2010", 30, 15, 12, 13] ];

im using jackson library , create jsongenerator, code have:

string[] cols = new string[5]; //number of study 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 same next rows... jgenerator.writeendarray();

the problem when setting first value error:

org.codehaus.jackson.jsongenerationexception: can not write field name, expecting value

can build array object before writing it, rather bothering individual pieces?

objectmapper mapper = new objectmapper(); arraynode array = mapper.createarraynode(); int = 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 several megabytes of info or tight memory constraints, might turn out more maintainable well.

java json jackson

No comments:

Post a Comment