【发布时间】:2021-03-18 16:49:08
【问题描述】:
我正在尝试使用 Jackson Streaming API 创建 JSON。我知道如何使用 Jackson 在 JSON 中创建元素数组,因为我们有很多与之相关的示例。但是我对如何使用它创建一个对象数组有点困惑。
下面是我最后想要得到的JSON结构:
{
"name" : "Batman",
"year" : 2008,
"writers":[
{
"name" : "Nolan",
"age" : 49
},
{
"name" : "Johnathan",
"age" : 35
}
]
}
以下是我的代码:
import org.json.JSONObject;
import com.fasterxml.jackson.core.JsonEncoding;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.ObjectMapper;
public class HelloWorld {
public static void main(String[] args) throws IOException {
ObjectMapper mapper = new ObjectMapper();
ByteArrayOutputStream jsonStream = new ByteArrayOutputStream();
JsonGenerator jsonGenerator = mapper.getFactory().createGenerator(jsonStream, JsonEncoding.UTF8);
jsonGenerator.writeStartObject();
jsonGenerator.writeStringField("name", "Batman");
jsonGenerator.writeNumberField("year", 2008);
jsonGenerator.writeFieldName("writers");
jsonGenerator.writeStartArray();
// How to to create here objects and add it to the "writers"
// Should I create another JsonGenerator and create objects usign it?
jsonGenerator.writeEndArray();
jsonGenerator.writeEndObject();
jsonGenerator.close();
String jsonData = new String(jsonStream.toByteArray(), "UTF-8");
JSONObject json = new JSONObject(jsonData);
System.out.println(json.toString(4));
}
}
有人可以指导我如何创建对象并将它们一一添加到数组中吗?我找不到这样的例子,所以在这里发布。
【问题讨论】:
-
仍在寻找答案。任何使用
Jackson Streaming API的帮助都会有所帮助。