我如何用org.JSON在Java中制作一个JSON,它看起来确实像这个例子



所以,我尝试了一些类似java的东西,但输出看起来不太好。

我试图用制作json文件的一个代码示例

String name = "usericals.json";
JSONObject jsonObj = new JSONObject();
JSONArray scene = new JSONArray();
JSONArray element = new JSONArray();

jsonObj.put("scene", scene);
for (int i = 0; i < 1; i++) {
for (int ii = 0; ii < 1; ii++) {
element.put(write);
}
jsonObj.put("element", element);
}
scene.put(element);
try (PrintWriter writer = new PrintWriter("new.json", "UTF-8")) {
writer.write(jsonObj.toString(4));
} catch (Exception ex) {
System.out.println("exception " + ex);
}

我想制作一个json文件,看起来像这样,但我做不好。我正在用我的代码创建数组。有人有什么想法或建议吗?

我想要的JSON文件:

{
"scene": [
{
"id": 0,
"calendar_event": "urlaub",
"element": [
{
"anything": ""
},
{
"anything": ""
}
]
},
{
"id": 1,
"calendar_event": "urlauburlaub",
"element": [
{
"anything": ""
},
{
"anything": ""
}
]
},
{
"id": 2,
"calendar_event": "urlauburlauburlaub",
"element": [
{
"anything": ""
},
{
"device": "",
"anything": ""
}
]
},
{
"id": 3,
"calendar_event": "urlauburlauburlauburlaub",
"element": [
{
"anything": ""
},
{
"anything": ""
}
]
}
]
}

我建议使用库。杰克逊或葛兰素史克是个不错的选择。

您可以创建POJO,然后使用Jackson的ObjectMapper,而不是逐个字段手动创建json。示例:

public class Car {
private String color;
private String type;
// standard getters setters
}

然后

ObjectMapper objectMapper = new ObjectMapper();
Car car = new Car("yellow", "renault");
objectMapper.writeValue(new File("target/car.json"), car);

这将提供

{"color":"yellow","type":"renault"}

谷歌有很多杰克逊教程!

递归使用JSONObject。试试这样的东西(我添加了一些额外的缩进,这样就可以很容易地阅读,但在实际项目中,最好使用函数(:

JSONObject json = new JSONObject();
JSONArray scene = new JSONArray();
JSONObject node = new JSONObject();
node.put("id", 0);
node.put("calendar_event", "urlaub");
JSONArray element = new JSONArray();
JSONObject enode = new JSONObject();
enode.put("anything", "");
element.add(enode);
//...
node.put("element", element);
scene.add(node);
json.put("scene", scene);
//...

请注意,您可以手动生成json,但也有其他库可以扫描对象来生成json。根据你的需要,它可能会更容易,但请记住,这样做会让你的所有开销都增加,因为你需要在内存中保存同一棵树的两个副本。同样处理层次结构可能是使用普通java对象的一个问题。

最新更新