我想使用 JSONObject 和 JSONArray 构建一个类似于遵循 java 中的结构的 JSON 对象。我该怎么做?

I want to build a JSON Object similar to following the structure in java using JSONObject and JSONArray. How can I do it?

这是json。 类似于 Creating nested JSON object for the following structure in Java using JSONObject? 的东西会有所帮助。

{
      "taskAssings": [
        {
          "taskAssigned": {
            "id": "3c814009-82f7-4246-bc51-2d263e758561"
          },
          "taskAssignee": {
            "id": "3c814009-82f7-4246-bc51-2d263e758561"
          }
        }
      ],
      "description": "TestTaskDescription",
      "assignTo": {
        "id": "3c814009-82f7-4246-bc51-2d263e758561"
      },
      "name": "taskname",
      "status": {
        "id": "7d8a0d80-5c93-46cc-982d-47399503beaa"
      },
      "priority": {
        "id": "842a9a9c-4a1a-4f70-bf4d-8181b482f651"
      }
    }

你可以试试JSONSimple library,然后用这种方式形成对象-

您必须导入 org.json.simple.JSONArrayorg.json.simple.JSONObject 才能使用此代码。

    JSONObject object=new JSONObject();

    JSONObject holder=new JSONObject();
    JSONArray taskAssings = new JSONArray();

    JSONObject taskAssigned=new JSONObject();
    taskAssigned.put("id", "3c814009-82f7-4246-bc51-2d263e758561");

    JSONObject taskAssignee=new JSONObject();
    taskAssignee.put("id", "3c814009-82f7-4246-bc51-2d263e758561");

    holder.put("taskAssigned",taskAssigned);
    holder.put("taskAssignee",taskAssignee);
    taskAssings.add(holder);

    object.put("taskAssings", taskAssings);

    JSONObject status=new JSONObject();
    status.put("id", "7d8a0d80-5c93-46cc-982d-47399503beaa");
    object.put("status", status);

    JSONObject assignTo=new JSONObject();
    assignTo.put("id", "3c814009-82f7-4246-bc51-2d263e758561");
    object.put("assignTo", assignTo);


    JSONObject priority=new JSONObject();
    priority.put("id", "842a9a9c-4a1a-4f70-bf4d-8181b482f651");
    object.put("priority",priority);

    object.put("description", "TestTaskDescription");
    object.put("name", "taskname");