Hi Guys [Java and Android新手]
我有一个php脚本,它会发出像这样的json响应
echo json_encode(array($camparray));
json数组就像这样
[
{
"0":{"url":"10007.jpg","cmpname":"Romain Jerome"},
"2":{"url":"10023.jpg","cmpname":"NGO"},
"3":{"url":"10024.jpg","cmpname":"Save The Children"},
"4":{"url":"10039.jpg","cmpname":"John Deere"},
"5":{"url":"10039.jpg","cmpname":"Starbucks"}
}
]
现在我正在使用凌空来获得回复。我在某种程度上无法迭代数组。请帮忙..
@Override
public void onResponse(JSONObject response) {
Toast.makeText(getApplicationContext(),"On Response Try block",Toast.LENGTH_SHORT).show();
try {
JSONArray camps = response.getJSONArray("camparray");
// insert for loop here...
//String pinusers = response.getString("mobileno");
//Toast.makeText(getApplicationContext(),"On Response Try block"+pinusers,Toast.LENGTH_SHORT).show();
if(camps!= null){
JSONObject jsonObj = new JSONObject("camps");
JSONArray cmpz = jsonObj.getJSONArray("camparray");
for (int i = 0; i < cmpz.length(); i++) {
JSONObject c = cmpz.getJSONObject(i);
String id = c.getString("url");
String name = c.getString("cmpname");
Toast.makeText(getApplicationContext(),"On Response Try bitch"+id+name,Toast.LENGTH_SHORT).show();
}
}
else {
Toast.makeText(getApplicationContext(),"Camp NULL",Toast.LENGTH_SHORT).show();
}
}
catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),"Try Fail NULL",Toast.LENGTH_SHORT).show();
}
}
我不明白为什么它已经过了几个小时而且我无法破解它。我想有些概念问题......
答案 0 :(得分:0)
首先,您对服务器的响应采用错误的结构化格式。仍然,要获取此响应的内容,您可以使用此:
if(camps!= null){
JSONArray cmpz = new JSONArray("camparray");
JSONObject jsonObj = cmpz.getJSONObject(0);
String zero = jsonObj.getString("0");
JSONObject vZero = new JSONObject(zero);
String zeroUrl = vZero.getString("url");
String cmpnameZero = vZero.getString("cmpname");
String two = jsonObj.getString("2");
JSONObject vTwo = new JSONObject(two);
String twoUrl = vTwo.getString("url");
String cmpnameTwo = vTwo.getString("cmpname");
String three = jsonObj.getString("3");
JSONObject vThree = new JSONObject(three);
String threeUrl = vThree.getString("url");
String cmpnamTthree = vThree.getString("cmpname");
//Similarly get value for 4 and 5 and do whatever you want with those variables
}