android解析这样的json数组
{"posttitle":"11","postusername":"杨伟"}{"posttitle":"22","postusername":"杨伟"}返回值是这样,在a...
{"posttitle":"11","postusername":"杨伟"}{"posttitle":"22","postusername":"杨伟"} 返回值是这样,在android中怎样解析?怎样转变为JSONArray
展开
展开全部
我做了一个代码如下:
public class MainActivity extends Activity {
ListView listview;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listview = (ListView) findViewById(R.id.listview);
String temp = "[{\"aa\":\"1\",\"bb\":\"2\"},{\"aa\":\"3\",\"bb\":\"4\"},{\"aa\":\"5\",\"bb\":\"6\"}]";
List<Map<String, Object>> data = getList(temp);
SimpleAdapter adapter = new SimpleAdapter(this, data, R.layout.item, new String[]{"aa","bb"}, new int[]{R.id.aa,R.id.bb});
listview.setAdapter(adapter);
}
public Map<String, Object> getMap(String jsonString) {
JSONObject jsonObject;
try {
jsonObject = new JSONObject(jsonString);
@SuppressWarnings("unchecked")
Iterator<String> keyIter = jsonObject.keys();
String key;
Object value;
Map<String, Object> valueMap = new HashMap<String, Object>();
while (keyIter.hasNext()) {
key = (String) keyIter.next();
value = jsonObject.get(key);
valueMap.put(key, value);
}
return valueMap;
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
public List<Map<String, Object>> getList(String jsonString) {
List<Map<String, Object>> list = null;
try {
JSONArray jsonArray = new JSONArray(jsonString);
JSONObject jsonObject;
list = new ArrayList<Map<String, Object>>();
for (int i = 0; i < jsonArray.length(); i++) {
jsonObject = jsonArray.getJSONObject(i);
list.add(getMap(jsonObject.toString()));
}
} catch (Exception e) {
e.printStackTrace();
}
return list;
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询
广告 您可能关注的内容 |