簡體   English   中英

獲取特定的json值http發布android studio

[英]get particular json value http post android studio

我是android開發的初學者。 我已經上傳了文件,並從服務器獲得響應。 但是,響應包含我不需要的值。 服務器響應為:值{“ time_used”:53840,“ result_idcard”:{“ index1”:0,“ index2”:0,“ confidence”:87.42464,“}}。

我只想要置信度。 我該如何提取呢? 當我運行下面的代碼時,logcat顯示:

錯誤:org.json.JSONObject類型的org.json.JSONException無法轉換為JSONArray。

請幫我..

/ ** *將文件上傳到服務器* /

private class UploadFileToServer extends AsyncTask<Void, Integer, String> {
    String docPath= null;
    String facePath=null;

    public UploadFileToServer(String docPath, String facePath) throws JSONException {
        this.docPath = docPath;
        this.facePath = facePath;

            }

    @Override
    protected void onPreExecute() {

        // setting progress bar to zero
        progressBar.setProgress(0);
        super.onPreExecute();
    }

    @Override
    protected void onProgressUpdate(Integer... progress) {
        // Making progress bar visible
        progressBar.setVisibility(View.VISIBLE);

        // updating progress bar value
        progressBar.setProgress(progress[0]);

        // updating percentage value
        txtPercentage.setText(String.valueOf(progress[0]) + "%");


        //code to show progress in notification bar
        FileUploadNotification fileUploadNotification = new FileUploadNotification(UploadActivity.this);
        fileUploadNotification.updateNotification(String.valueOf(progress[0]), "Image 123.jpg", "Camera Upload");


    }

    @Override
    protected String doInBackground(Void... params) {
        return uploadFile();
    }

    @SuppressWarnings("deprecation")
    public String uploadFile() {

        String responseString = null;

        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(Config.FILE_UPLOAD_URL);

        try {
            AndroidMultiPartEntity entity = new AndroidMultiPartEntity(
                    new ProgressListener() {

                        @Override
                        public void transferred(long num) {
                            publishProgress((int) ((num / (float) totalSize) * 100));
                        }
                    });


            entity.addPart("imageIdCard", new FileBody(new File(docPath)));
            entity.addPart("imageBest", new FileBody(new File(facePath)));


            totalSize = entity.getContentLength();
            httppost.setEntity(entity);


            // Making server call
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity r_entity = response.getEntity();

            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == 200) {
                // Server response

                responseString = EntityUtils.toString(r_entity);

            } else {
                responseString = "Error occurred! Http Status Code: "
                        + statusCode;
            }

        } catch (ClientProtocolException e) {
            responseString = e.toString();
        } catch (IOException e) {
            responseString = e.toString();
        }

        return responseString;
    }

                @Override
    protected void onPostExecute(String result) {

        //super.onPostExecute(result);

        //if (result != null)

                    try
                    {
                        //Convert response string to Json Array
                        JSONArray ja = new JSONArray(result);

                        //Iterate through and retrieve club fields
                        int n = ja.length();
                        for (int i = 0; i < n; i++) {

                            //Get individual Json object from Json Array
                            JSONObject jo = ja.getJSONObject(i);

                            //Retrieve each Json object's fields
                            String request_id = jo.getString("request_id");
                            Double confidence = jo.getDouble("confidence");

                            //float confidence= BigDecimal.valueOf(jo.getDouble("result_idcard/confidence")).floatValue();
                        }
                    } catch (JSONException e) {
                        Log.e("JSONException", "Error: " + e.toString());
                    }
                    //Log.e(TAG, "Response from server: " + result);

                    // showing the server response in an alert dialog
                    showAlert(result);
                }
}

這是服務器進行更改之前的響應

您正在將JSON結果轉換為JSONArray但結果只是一個對象。 因此,直接將其解析為對象並獲取所需的節點。 而且, result_idcard是object,您還需要將其轉換為JSONObject然后獲取confidence節點。

嘗試這個:

@Override
protected void onPostExecute(String result) {
     try {
        JSONObject jsonObject = new JSONObject(result);

        //Retrieve each Json object's fields
        JSONObject request_id = jsonObject.getJSONObject("result_idcard");
        Double confidence = request_id.getDouble("confidence");

        showAlert(confidence);
     } catch (JSONException e) {
        e.printStackTrace();
     }
}

基於OP的問題(到目前為止)和OP提供的(無效的)JSON示例,OP提供了一些我可以嘗試的小測試。 也許OP將了解其工作原理。

只需將這段代碼放在您的活動中的某個地方,然后調用startJsonTest(); 您將在logcat中看到響應。

private void startJsonTest(){
    // The JSON the OP provide in their question!
    String json = "{'time_use':53840,'result_idcard':{'index1':0,'index2':0,'confidence':87.42464}}";
    testYourJson(json);
}

private void testYourJson(String result) {
    try {
        if(result == null || result.isEmpty()){
            Log.e("testYourJson", "Something went wrong!");
            return;
        }

        Log.e("testYourJson", result);

        JSONObject jsonObject = new JSONObject(result);
        //Retrieve each Json object's fields
        int time = jsonObject.optInt("time_use", -1);
        Log.e("testYourJson", "time = " + time);
        JSONObject request_id = jsonObject.getJSONObject("result_idcard");

        Double confidence = request_id.optDouble("confidence", -222.0f);
        int index1 = request_id.optInt("index1", -1);
        int index2 = request_id.optInt("index2", -1);

        // Show a little confidence ;-)
        Log.e("testYourJson", "confidence  = " + confidence);
        Log.e("testYourJson", "index1  = " + index1);
        Log.e("testYourJson", "index2  = " + index2);
    } catch (JSONException e) {
        Log.e("testYourJson", e.getMessage());
    }
}

optDouble 解決方案的唯一區別(正確)是我使用了optIntoptDouble因為您可以替換可選值。

這可行! 我已經測試過了 但是我懷疑您擁有的JSON與您提供的JSON不同。 祝好運!

編輯在仔細觀察了一下HARD的屏幕快照后,OP鏈接到他的Question,看來index1index2實際上是Double值! 因此實際的工作代碼需要對此進行補償!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM