[英]JSONGenerator How to output an object in the JSON
I want to output the following JSON:我想输出以下 JSON:
result: {
"x": 11,
"y": 10,
"actions": [
],
"localConfigurations": {
"local1": {},
"local2": {}
}
}
I have the following code:我有以下代码:
public class Configuration {
private int fX;
private int fY;
private Actions[] fActions;
private LinkedHashMap<String, LocalConfiguration> fLocalConfigurations = new LinkedHashMap<>();
@JsonProperty("x")
public int getX() { return fX; }
public void setX(int x) { fX = x; }
@JsonProperty("y")
// getter and setter for y
@JsonProperty("actions")
// getter and setter for actions
@JsonProperty("localConfigurations")
// getter and setter for localConfigurations
}
Below is the code that I am trying to use to output the JSON:下面是我试图用来输出 JSON 的代码:
JsonFactory factory = new JsonFactory();
JsonGenerator generator = factory.createGenerator(fOutputStream);
generator.writeStartObject();
generator.writeArrayFieldStart("result");
if (configuration != null)
mapper.writeValue(generator, configuration);
generator.writeEndArray();
generator.writeEndObject();
generator.close();
However, my output turns out as:但是,我的输出结果为:
result: [{
"x": 11,
"y": 10,
"actions": [
],
"localConfigurations": {
"local1": {},
"local2": {}
}
}]
I am not sure how I can achieve the desired output, without using the generator.writeArrayFieldStart.我不确定如何在不使用 generator.writeArrayFieldStart 的情况下实现所需的输出。 If I use only writeStartObject and dump the object Configuration, the JSON output throws some errors instead.如果我只使用 writeStartObject 并转储对象配置,则 JSON 输出会引发一些错误。 So, how can I get the output as I want?那么,我怎样才能得到我想要的输出呢? thanks谢谢
You need to open object, write property, write Configuration
POJO
and close object.您需要打开对象,写入属性,写入Configuration
POJO
并关闭对象。
generator.writeStartObject();
generator.writeFieldName("result");
objectMapper.writeValue(generator, configuration);
generator.writeEndObject();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.