如何创建对象的 JSONObject?安卓

Edu*_*nfa 4 java android json

我想创建一个JSONObject像这样的:

[
   {
       id:01,
       name:"John",
       number:010
   },
   {
       id:02,
       name:"Mike",
       number: 020
   }
]
Run Code Online (Sandbox Code Playgroud)

这是我的代码:

public void equipmentViewed(List<Equipment> equipmentSelected, final OnControlResponseListener listener, String description, Equipment equipment) throws JSONException {
        wsAccessControl = WSAccessControl.getInstance();

        EquipmentViewed equipmentViewed = new EquipmentViewed();
        equipmentViewed.setEquipment(equipmentsCount(equipmentSelected));

        JSONObject jsonObject = new JSONObject();

        try {
            jsonObject.put("", new JSONArray(equipmentViewed.getEquipment().toString()));
        } catch (JSONException e) {
            Log.e(TAG, "Failed to create json object. Cause: " + e.getMessage());
        }
        String url = Constants.PROVIDER_DOMAIN_URL + Constants.REQUEST_EQUIPMENT;
        wsAccessControl.makeWSRequest(RequestType.POST, url, jsonObject, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                listener.OnResponseReceived(response);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                listener.OnResponseError(error);
            }
        }, true);
    }
Run Code Online (Sandbox Code Playgroud)

其中EquipmentViewed包含String设备列表。

Moh*_*uag 5

您可以使用以下命令创建所需的 JSON:

JSONArray array = new JSONArray();

JSONObject obj1 = new JSONObject();
obj1.put("id", "01");
obj1.put("name", "John");
obj1.put("number", "010");

JSONObject obj2 = new JSONObject();
obj2.put("id", "02");
obj2.put("name", "Mike");
obj2.put("number", "020");

array.put(obj1);
array.put(obj2);

/* array = [
              {
                   id:01,
                   name:"John",
                   number:010
               },
               {
                   id:02,
                   name:"Mike",
                   number: 020
               }
           ]
  */
Run Code Online (Sandbox Code Playgroud)