简体   繁体   English

获取特定的json值http发布android studio

[英]get particular json value http post android studio

I am a beginner in android development. 我是android开发的初学者。 I have upload the file, and get the response from server. 我已经上传了文件,并从服务器获得响应。 However, the response contains the value that I dont want. 但是,响应包含我不需要的值。 The server response as: Value {"time_used":53840,"result_idcard":{"index1":0,"index2":0,"confidence":87.42464,"}}. 服务器响应为:值{“ time_used”:53840,“ result_idcard”:{“ index1”:0,“ index2”:0,“ confidence”:87.42464,“}}。

I only want the confidence level only. 我只想要置信度。 How I can extract that? 我该如何提取呢? When I run the code below, the logcat shows: 当我运行下面的代码时,logcat显示:

Error: org.json.JSONException of type org.json.JSONObject cannot be converted to JSONArray. 错误:org.json.JSONObject类型的org.json.JSONException无法转换为JSONArray。

Please help me.. 请帮我..

/** * Uploading the file to server */ / ** *将文件上传到服务器* /

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 这是服务器进行更改之前的响应

You're converting the JSON result to JSONArray but the result is just an object. 您正在将JSON结果转换为JSONArray但结果只是一个对象。 So directly parse it to object and get the nodes you need. 因此,直接将其解析为对象并获取所需的节点。 And also, the result_idcard is object, you also need to convert it to JSONObject then get the confidence node. 而且, result_idcard是object,您还需要将其转换为JSONObject然后获取confidence节点。

Try this: 尝试这个:

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

Based on the OP's question (so far) and the (invalid) JSON example the OP provided I have hacked out a little test for them to try. 基于OP的问题(到目前为止)和OP提供的(无效的)JSON示例,OP提供了一些我可以尝试的小测试。 Perhaps the OP will get the idea of how this works. 也许OP将了解其工作原理。

Just put this code somewhere in you activity and call startJsonTest(); 只需将这段代码放在您的活动中的某个地方,然后调用startJsonTest(); . You will see the response in the logcat. 您将在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());
    }
}

The only difference to Tenten's solution (which is correct) is that I have used optInt and optDouble because you can substitute optional values. optDouble 解决方案的唯一区别(正确)是我使用了optIntoptDouble因为您可以替换可选值。

This works! 这可行! I have tested it. 我已经测试过了 But I suspect that the JSON you have is different to what you provide. 但是我怀疑您拥有的JSON与您提供的JSON不同。 Good Luck! 祝好运!

EDIT After taking a good long HARD look at the screen shot the OP has linked to his Question it appears as if index1 and index2 are actually Double values! 编辑在仔细观察了一下HARD的屏幕快照后,OP链接到他的Question,看来index1index2实际上是Double值! so the actual working code would need to compensate for that! 因此实际的工作代码需要对此进行补偿!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM