得到特别的json值http post android studio

问题描述 投票:-1回答:2

我是android开发的初学者。我上传了文件,并从服务器获取响应。但是,响应包含我不想要的值。服务器响应为:值{“time_used”:53840,“result_idcard”:{“index1”:0,“index2”:0,“置信度”: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);
                }
}

this is the response from server before making the changes

java android json http-post
2个回答
1
投票

您将JSON结果转换为JSONArray,但结果只是一个对象。因此,直接将其解析为对象并获取所需的节点。而且,result_idcard是对象,你还需要将其转换为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();
     }
}

1
投票

基于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());
    }
}

与Tenten的解决方案(这是正确的)的唯一区别是我使用了optIntoptDouble,因为你可以替换可选值。

这有效!我测试了它。但我怀疑你拥有的JSON与你提供的不同。祝好运!

编辑经过长时间的硬看看屏幕截图,OP已经链接到他的问题,看起来好像index1index2实际上是Double值!所以实际工作代码需要补偿!

© www.soinside.com 2019 - 2024. All rights reserved.