【问题标题】:Android httpGET JSON arrayAndroid httpGET JSON 数组
【发布时间】:2014-11-16 10:31:54
【问题描述】:

目标:调用此函数并查看从 php 返回的 JSON 数组,看看 element[0] 或 [1] == 1。PHP 查询布尔值表,我想知道其中的 1 和 0为了继续功能。

我有这个函数来执行 httpGET 并返回一个 JSON 对象

  class CheckVotingStatus extends AsyncTask<String, String, String> {

    /**
     * Before starting background thread Show Progress Dialog
     * */
    boolean failure = false;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(Vote.this);
        pDialog.setMessage("Checking vote Status...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.show();
    }

    @Override
    protected String doInBackground(String... args) {
        // TODO Auto-generated method stub
        // Check for success tag
        int success;

        try {
            // Building Parameters


            Log.d("request!", "starting");
            // getting product details by making HTTP request
            JSONObject json = jParser.getJSONFromUrl(LOGIN_URL);

            // check your log for json response
           // Log.d("Login attempt", json.toString());

            // json success tag
            success = json.getInt(TAG_SUCCESS);

            if (success == 1) {
               // Log.d("Login Successful!", json.toString());

                JSONArray answerObj = json.getJSONArray(TAG_ANSWER);

                // get first product object from JSON Array
               JSONObject answer = answerObj.getJSONObject(0);
                String bool1s = answer.getString(TAG_BOOL1);
                JSONObject answer2 = answerObj.getJSONObject(1);
                String bool2s = answer2.getString(TAG_BOOL2);

                /******************************************/
                if (bool1s.equals("1")&& bool2s.equals("0"))
                {
                   startVoting = true;
                }
                else if (bool1s.equals("0")&& bool2s.equals("1"))
                {
                    endVoting = true;
                    voted = false;

                }
                /*******************************************/
                //return json.getString(TAG_MESSAGE);
            }
            else
            {
                //Log.d("Login Failure!", json.getString(TAG_MESSAGE));
                //return json.getString(TAG_MESSAGE);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }

    protected void onPostExecute(String file_url) {
        // dismiss the dialog once product deleted
        pDialog.dismiss();
        if (file_url != null){
            Toast.makeText(Vote.this, file_url, Toast.LENGTH_LONG).show();
        }

    }

我的 PHP 页面查询从数据库返回两个布尔值

$response = array();
$resttt = "SELECT startingBool, endingBool FROM vote_count";
$result = mysql_query("$resttt");
if (mysql_num_rows($result) > 0) {

    $result = mysql_fetch_array($result);

    $answer = array();
    $answer["startingBool"] = $result["startingBool"];            
    $answer["endingBool"] = $result["endingBool"];
    // success
    $response["success"] = 1;

    $response["answer"] = array();

    array_push($response["answer"], $answer);

    // echoing JSON response
    echo json_encode($response);

}

我得到一个输入异常的结束和一个错误,因为没有答案的价值

JSON 解析器

 public JSONObject getJSONFromUrl(final String url) {


    // Making HTTP request
    try {
        // Construct the client and the HTTP request.
        //DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpClient httpClient = createHttpClient();
        HttpGet httpGet = new HttpGet(url);
        // Execute the POST request and store the response locally.
        HttpResponse httpResponse = httpClient.execute(httpGet);
        // Extract data from the response.
        HttpEntity httpEntity = httpResponse.getEntity();
        // Open an inputStream with the data content.
        is = httpEntity.getContent();

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        // Create a BufferedReader to parse through the inputStream.
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "iso-8859-1"), 8);
        // Declare a string builder to help with the parsing.
        StringBuilder sb = new StringBuilder();
        // Declare a string to store the JSON object data in string form.
        String line = null;

        // Build the string until null.
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }

        // Close the input stream.
        is.close();
        // Convert the string builder data to an actual string.
        json = sb.toString();
    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }

    // Try to parse the string to a JSON object
    try {
        Log.v("JSON", json);
        jObj = new JSONObject(json);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

    // Return the JSON Object.
    return jObj;

}

【问题讨论】:

  • 你看过 GSON 吗??

标签: java php android https


【解决方案1】:

当你有 jsonarray 时尝试获取值

JSONArray json = jParser.getJSONFromUrl(LOGIN_URL);
JSONObject json_obj = json.getJSONObject(0); 
String bool1s = json_obj.getString(TAG_BOOL1);
String bool2s = json_obj.getString(TAG_BOOL2);

【讨论】:

    【解决方案2】:

    你的 php 回显应该是这样的

    {"成功":1,"answer":[{"bool1":"0","bool2":"1"}]}

    和你的 php 脚本

    //conect to database, create table bool_table, insert data to bool_table.......
    
    
    $response = array();
    $resttt = "SELECT bool1, bool2 FROM bool_table";
    $result = mysql_query("$resttt");
    if (mysql_num_rows($result) > 0) {
    
            $result = mysql_fetch_array($result);
    
            $answer = array();
            $answer["bool1"] = $result["bool1"];            
            $answer["bool2"] = $result["bool2"];
            // success
            $response["success"] = 1;
    
            $response["answer"] = array();
    
            array_push($response["answer"], $answer);
    
            // echoing JSON response
            echo json_encode($response);
    
        }
    

    并解析 JSON

    private static final String TAG_SUCCESS = "success";
    private static final String TAG_ANSWER = "answer";
    private static final String TAG_BOOL1 = "bool1";
    private static final String TAG_BOOL2 = "bool2";
    int success;
    
    ......
    ...
    
    
                        JSONObject json = jsonParser.makeHttpRequest("xxxxxxxxxxxxxx", "GET", params);
    
                        // json success tag
                        success = json.getInt(TAG_SUCCESS);
                        if (success == 1) {
                            // successfully received product details
                            JSONArray answerObj = json.getJSONArray(TAG_ANSWER);
    
                            // get first product object from JSON Array
                            JSONObject answer = answerObj.getJSONObject(0);
    
    
                            String bool1s = answer.getString(TAG_BOOL1));
                            String bool2s = answer.getString(TAG_BOOL2));
                            }else{
                            .......
                            ....
    

    【讨论】:

    • 你解析json字符串,见上
    • 当你的响应是 {"success":1,"answer":[{"startingBool":"0","endingBool":"1"}]} 然后 JSONObject answer2 = answerObj.getJSONObject (0);只有一项数组,然后 String bool2s = answer2.getString(TAG_BOOL2);
    • 我的 JSONParser 返回 JSONObject
    • 是从jsonparser返回的吗?
    • this [{"startingBool":"1","endingBool":"0"}] 是 JSONArray 从我的解析器返回是这样的 {"answer":[{"startingBool":"1 ","endingBool":"0"}]}
    猜你喜欢
    • 1970-01-01
    • 2015-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-02
    • 1970-01-01
    相关资源
    最近更新 更多