如何解析 android 中 php 关联数组的 JSON 响应?

how to parse JSON response from php associated array in android?

我向 php 服务器发送了一个 android 请求,它在 JSON 中发送了一个关联的数组,如何将其解析为模型或其他方式进行改造或截击? JSON 回复如下:

{
   "d": {
      "240": {
         "title": "First floor",
         "rooms": {
            "246": {
               "title": "kitchen",
               "type": 1,
               "hid": 246
            },
            "251": {
               "title": "room56",
               "type": 3,
               "hid": 251
            }
         }
      },
      "389": {
         "title": "Second   floor",
         "rooms": {
            "390": {
               "title": "First room",
               "type": 2,
               "hid": 390
            }
         }
      }
   }
}

如果你使用 volley,你可以通过 JSONRequest 获得一个 json 对象(或者如果你使用 Retrofit 你可以将 String 转换为 json 对象)然后使用我的代码来获取数组。 (如有任何问题请评论或联系我:nhat.thtb@gmail.com)

     protected ArrayList<Floor> parse(JSONObject json_response) {

    ArrayList<Floor> list_floor = new ArrayList<>();

    try {
        JSONObject json_d = json_response.getJSONObject("d");
        Iterator<String> iter = json_d.keys();
        while (iter.hasNext()) {
            String key = iter.next();
            JSONObject json_floor = json_d.getJSONObject(key);
            Floor floor = new Floor();
            floor.parse(json_floor);
            list_floor.add(floor);
        }
    } catch (Exception e) {

    }

    return list_floor;

}

 public class Entity {
    public void parse(JSONObject json) {

    }
}

public class Floor extends Entity {
    private String mTitle;
    private ArrayList<Room> mListRoom;

    @Override
    public void parse(JSONObject json) {
        try {
            mTitle = json.getString("title");
            mListRoom = new ArrayList<>();
            JSONObject js_room = json.getJSONObject("rooms");
            Iterator<String> iter = js_room.keys();
            while (iter.hasNext()) {
                String key = iter.next();
                JSONObject js_room_tmp = json.getJSONObject(key);
                Room room = new Room();
                room.parse(js_room_tmp);
                mListRoom.add(room);
            }
        } catch (Exception e) {

        }
    }

    // setter and getter
}

public class Room extends Entity {
    private String mTitle;
    private int mType;
    private int mHid;

    @Override
    public void parse(JSONObject json) {
        try {
            mTitle = json.getString("title");
            mType = json.getInt("type");
            mHid = json.getInt("hid");
        } catch (Exception e) {

        }
    }
    // setter and getter

}