繁体   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