单数据{'singer':{'id':01,'name':'tom','gender':'男'}}
多个数据{"singers":[
{'id':02,'name':'tom','gender':'男'},
{'id':03,'name':'jerry,'gender':'男'},
{'id':04,'name':'jim,'gender':'男'},
{'id':05,'name':'lily,'gender':'女'}]} // 普通Json数据解析
private void parseJson(String strResult) {
try {
JSONObject jsonObj = new JSONObject(strResult).getJSONObject("singer");
int id = jsonObj.getInt("id");
String name = jsonObj.getString("name");
String gender = jsonObj.getString("gender");
tvJson.setText("ID号"+id + ", 姓名:" + name + ",性别:" + gender);
} catch (JSONException e) {
System.out.println("Json parse error");
e.printStackTrace();
}
}
//解析多个数据的Json
private void parseJsonMulti(String strResult) {
try {
JSONArray jsonObjs = new JSONObject(strResult).getJSONArray("singers");
String s = "";
for(int i = 0; i < jsonObjs.length() ; i++){
JSONObject jsonObj = ((JSONObject)jsonObjs.opt(i)).getJSONObject("singer");
int id = jsonObj.getInt("id");
String name = jsonObj.getString("name");
String gender = jsonObj.getString("gender");
s += "ID号"+id + ", 姓名:" + name + ",性别:" + gender+ "\n" ;
}
tvJson.setText(s);
} catch (JSONException e) {
System.out.println("Jsons parse error !");
e.printStackTrace();
}
}