Android adding Json objects into an Array

前端 未结 2 1147
一生所求
一生所求 2021-01-22 11:31

What I\'m trying to do is create a JSONObject that contains an Array of other JSONObjects that are organized by a String? for example i want to create a JSONObject that contains

2条回答
  •  日久生厌
    2021-01-22 11:46

    From what you say, you seem like trying to build a JSONArray out of some JSONObjects. This might help:

    public void writeJSON() {
        JSONObject user = new JSONObject();
        JSONObject user2;
        user2 = new JSONObject();
        try {
            user.put("dish_id", "1");
            user.put("dish_custom", "2");
            user.put("quantity", "2");
            user.put("shared", "2");
    
            user2.put("dish_id", "2");
            user2.put("dish_custom", "2");
            user2.put("quantity", "4");
            user2.put("shared", "3");
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    
        JSONArray notebookUsers = new JSONArray();
        notebookUsers.put(user);
        notebookUsers.put(user2);
        System.out.println("the JSON ARRAY is"+notebookUsers);
    

    Here 2 json objects are added to 1 JSONArray.

    The output of the System.out.println will look something like this:

    the JSON ARRAY is[{"shared":"2","dish_custom":"2","dish_id":"1","quantity":"2"},{"shared":"3","dish_custom":"2","dish_id":"2","quantity":"4"}]
    

    And the string comparison you are using is not right.

    if(matchDateTemp != matchDate1)
    

    u cannot compare strings like that. u can use something like:

    if(!(matchDateTemp.equals(matchDate1)))
    

提交回复
热议问题