我正在创建一个Android应用并试图读取从PHP(Laravel)返回的json数据。
这是PHP代码:
$id = $request->input('id');
$customer = Customer::find(array('id' => $id));
if(!isset($customer))
return json_encode(array('message'=>'empty'));
else
return json_encode(array('message'=>'found', 'customer' => $customer));
以下是我得到的JSON响应:
{"message":"found","customer":[{"id":1,"phone":"1234567890","name":"abc","photo":"","status":"active","created_at":"2016-01-18 09:23:10","updated_at":"-0001-11-30 00:00:00"}]}
以下是Android代码:
client.get(Utility.server + "/get-customer-info", params, new AsyncHttpResponseHandler() {
// When the response returned by REST has Http response code '200'
@Override
public void onSuccess(String response) {
try {
JSONObject obj = new JSONObject(response);
if (obj.getString("message").equals("found")) {
JSONObject customer = obj.getJSONObject("customer");
String id = customer.getString("id");
String name = customer.getString("name");
String phone = customer.getString("photo");
String photo = customer.getString("photo");
String status = customer.getString("status");
String createdAt = customer.getString("created_at");
Utility.customer = new Customer(id, name, phone, photo, status, createdAt);
Intent i = new Intent(SplashActivity.this, MainActivity.class);
startActivity(i);
}
else if (obj.getString("message").equals("empty")) {
Intent i = new Intent(SplashActivity.this, WelcomeActivity.class);
startActivity(i);
}
else {
Toast.makeText(getApplicationContext(), "Invalid data", Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "Error Occured [Server's JSON response might be invalid]!", Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
内部客户对象就像一个数组,我无法使用JSONObject或JSONArray读取它。我得到语句的类型不匹配错误:
JSONObject customer = obj.getJSONObject("customer");
答案 0 :(得分:1)
从您的JSON响应中可以清楚地看到它是JsonArray
而不是JsonObject
。像这样获得客户的第一个对象:
JSONArray customerArr = obj.getJSONArray("customer");
JsonObject customer=customerArr.getJSONObject(0);
如果您在客户数组中有多个数据,请使用for循环
for(int i=0;i<customerArr.length;i++)
{
JsonObject customer=customerArr.getJSONObject(i);
}
答案 1 :(得分:1)
将您的代码更改为以下方式
JSONObject obj = new JSONObject(response);
if (obj.getString("message").equals("found")) {
JSONArray customer = obj.getJSONArray("customer");
if (customer != null && customer.length() > 0) {
for (int kk = 0; kk <customer.length(); kk++) {
JSONObject json1 = customer.optJSONObject(kk);
String id = json1.getString("id");
String name = json1.getString("name");
String phone = json1.getString("photo");
String photo = json1.getString("photo");
String status = json1.getString("status");
String createdAt = json1.getString("created_at");
Utility.customer = new Customer(id, name, phone, photo, status, createdAt);
}
// your other code
}
}