How can I make an JSON in Java with org.json which does look like this example?

codemanian_helloworld :

So, I tried something with java which looks like this, but the output does not look nice.

One of the code-examples I tried to make a json file with:

        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);
        }

I wanted to make a json file which looks like this but I cannot get it right. I am creating with my code above only arrays. Does anyone have an idea or suggestion?

The JSON File I want:

{
  "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": ""
        }
      ]
    }
  ]
}
user1039663 :

Use JSONObject recursively. Try something like this (I add some extra indentation so it can be readed easily, but on real projects better use functions instead):

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);
//...

Note like this you generate manually the JSONs, but there are other libraries that scan objects to generate jsons. Depending on your needs, it could be easer, but remember that making so you are going to overhead everything because you are going to need to hold in memory two copies of the same tree. Also dealing with hierarchical structures maybe a problem using plain java objects.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=8161&siteId=1