说明:项目需求是请求数据后返回一个对象,但是对象有多少具体的元素确定不下来,在详情展示的时候,每一个元素就站位一行,数据随时会修改,为了方便后续维护做成listview显示每一项。
代码:
try {
Gson gson = new Gson();
String jsonStr = gson.toJson(mPlansBean);
JSONObject obj = new JSONObject(jsonStr);
Iterator it = obj.keys();
String vol = "";//值
String key = null;//键
while (it.hasNext()) {//遍历JSONObject
key = (String) it.next().toString();
vol = obj.getString(key);
mList.add(new SplitDetail(key, vol));
}
mAdapter = new SplitAdapter(mList, getActivity());
mLvDetail.setAdapter(mAdapter);
} catch (JSONException e) {
e.printStackTrace();
} catch (org.json.JSONException e) {
e.printStackTrace();
}
}
mPlansBean为请求来的数据对象,转成json字符串,然后拆分每一项为键和值,封装为:
public class SplitDetail {
private String key;
private String value;
public SplitDetail(String key, String value) {
this.key = key;
this.value = value;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
列表显示每一项键值。键不同可以映射成特定的字符。