Java 如何使用jackson创建json数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24280605/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 11:16:23  来源:igfitidea点击:

how to create json array using Hymanson

javajsonHymanson

提问by Victor Elizondo

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

我需要为报告创建一个 json 响应。像这样的东西:

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

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

我使用 Hymanson 库并创建了一个 JsonGenerator,这是我的代码:

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.Hymanson.JsonGenerationException: Can not write a field name, expecting a value

回答by Suresh

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

你需要这样的json吗...?

回答by Chris

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.

如果您不处理几兆字节的数据或非常严格的内存限制,那么这也可能更易于维护。