简体   繁体   English

如何使用Java jsonGenerator制作json文件?

[英]How can i make a json file with java jsonGenerator?

I try to make this json format: 我尝试制作这种json格式:

[{"x":1392440400000,"title":"!"},{"x":1392465600000,"title":"!"}]

I tried it out with the jsonGenerator 我用jsonGenerator尝试了

This is my code: 这是我的代码:

JsonFactory f = new JsonFactory();
StringWriter sw = new StringWriter();
JsonGenerator g = f.createJsonGenerator(sw);

    while {
     g.writeStartObject();
     g.writeNumberField("x",111111);
     g.writeStringField("title","!");
     g.writeEndObject();
    }

    g.close();
    return "["+sw.toString()+"]";   

But my output is like that ist like that: [{"x":1392440400000,"title":"!"} {"x":1392465600000,"title":"!"}] 但是我的输出就像这样的ist: [{"x":1392440400000,"title":"!"} {"x":1392465600000,"title":"!"}]

Can anybody help me to make the correct Json output with a comma between the objects ? 有人可以帮助我通过对象之间的逗号来生成正确的Json输出吗?

I'm not using jackson, but for this specific scenario, you need your g.writeStartObject(); 我没有使用杰克逊,但是对于这种特定情况,您需要g.writeStartObject(); and g.writeEndObject(); g.writeEndObject(); inside the loop. 在循环内。 (Because you're essentially trying to create an Array of Objects, right?) (因为您实际上是在尝试创建对象数组,对吗?)

You can use the ObjectMapper to generate the output. 您可以使用ObjectMapper生成输出。 So this could be something like this. 所以可能是这样的。

ObjectMapper mapper = new ObjectMapper();
HashMap<String, Object> data = new HashMap<String, Object>();
data.put("x", 1392440400000l);
data.put("title", "!");

HashMap<String, Object> data2 = new HashMap<String, Object>();
data2.put("x", 1392440400000l);
data2.put("title", "!");

List out = new ArrayList();
out.add(data);
out.add(data2);

String val = mapper.writeValueAsString(out);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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