在Android中从PHP接收JSON输出

时间:2015-09-08 06:55:21

标签: php android json

我在PHP脚本中使用此代码:

echo json_encode($output);

我在页面输出中得到以下内容:

[{"food_id":"1","food_description":"Free Range Egg","food_protein":"8"},{"food_id":"3","food_description":"Seeded Bread","food_protein":"6"}] 

请您告诉我如何在Android应用程序中接收页面输出并将其放入下面的对象中?例如:

food.setFood_id(c.getInt("food_id")); 

1 个答案:

答案 0 :(得分:0)

你需要做这样的事情......

JSONObject jsonObject = new JSONObject(response);// response is your json data which you are sending from php

JSONArray jsonArray = jsonObject.getJSONArray("mMessage");

for (int i = 0; i < jsonArray.length(); i++) {


    JSONObject jsonObj = jsonArray.getJSONObject(i);

    food.setFood_id(jsonObj.getInt("food_id"));
}

从php端你需要发送这样的数据

public function get_data()
{
    $json_response = array();
    $sql_querry_arry = array(); // array filled with sql result
        $json_response['mMessage'] = $sql_querry_arry;

    echo json_encode($json_response);
}

现在以字符串形式接收输出,并按照我之前提到的步骤进行操作