如何在ListView中使用JsonArray中每个JsonObject的2个属性?

时间:2015-05-13 07:36:36

标签: android json rest listview adapter

我向我的服务器发送请求,它返回JSONObject或JSONArray 我的JSONObject看起来像:

    {
    "place":
    {
        "plAddress1": "15th Street of Republic",
        "plAddress2": null,
        "plAddress3": null,
        "plCity": "Lyon",
        "plCountry": "France",
        "plId": 2,
        "plState": "Rhone",
        "plZipcode": "69000"
    },
    "vComplementsValues":
    [
    ],
    "vDepth": 0,
    "vDiameter": 15,
    "vFunction": "function",
    "vId": "VREVN0000001",
    "vInstallationdate": "2000-05-23T00:00:00",
    "vLastlatitude": 44.9278,
    "vLastlongitude": 4.90465,
    "vMaxnbrofrevolutions": 5,
    "vOpeningdirection": 0,
    "vStatus": "OPEN",
    "vWheelDiameter": 30,
    "vWheelType": "3 branches"
}

对于每个对象,我想填充ListView,此ListView仅显示ID和状态。我想保留其他属性,我将实现OnClick以显示有关该对象的所有信息。

感谢您的回答

2 个答案:

答案 0 :(得分:0)

这将是您的代码(如果您有任何问题要声明,请随时在评论中提问我):

JSONArray array = new JSONArray("your_json"); // you already have this code
            for(int i = 0; i < array.length(); i++) {
                JSONObject object = array.getJSONObject(i);
                //suppose you have long id and int status
                long id = object.optLong("id"); //your id name in json
                int status = object.optInt("status"); //your status name in json

                YourType item = new YourType(id, status);
                items.add(item);
            }
            adapter.notifyDataSetChanges();

重要:如果您的值没有long和int,请不要使用getString等方法,请使用optString等等

答案 1 :(得分:0)

从json对象填充列表。

   try {
         JSONArray array = new JSONArray(jsonArray);
         try {
         List<obj>listObj = new ArrayList<obj>();
         for(int i=0i<array.lenght;i++){
            JSONObject jobj= array.getJSONObject(i);
            if(jobj.getString("id")=!null&&jobj.getString("status")=!null){
            obj.setId(jobj.getString("id"));
            obj.status(jobj.getString("status"));
            }
            listobj.add(obj);
          }
                mAdapter.notifyDataSetChanged();
            } catch (Exception e) {
                Log.d("Error: ", e.getMessage());
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }


class obj {
String id;
String status;
}