JSON 解析错误(追加结果)

JSON Parsing Error (Appending Results)

这是我的 JSON 解析器 Class

public class JSONParser {

    String charset = "UTF-8";
    HttpURLConnection conn;
    DataOutputStream wr;
    StringBuilder result = new StringBuilder();
    URL urlObj;
    JSONObject jObj = null;
    StringBuilder sbParams;
    String paramsString;

    public JSONObject makeHttpRequest(String url, String method,
                                      HashMap<String, String> params) {

        sbParams = new StringBuilder();
        int i = 0;
        for (String key : params.keySet()) {
            try {
                if (i != 0){
                    sbParams.append("&");
                }
                sbParams.append(key).append("=")
                        .append(URLEncoder.encode(params.get(key), charset));

            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            i++;
        }

        if (method.equals("POST")) {
            // request method is POST
            try {
                urlObj = new URL(url);

                conn = (HttpURLConnection) urlObj.openConnection();

                conn.setDoOutput(true);

                conn.setRequestMethod("POST");

                conn.setRequestProperty("Accept-Charset", charset);

                conn.setReadTimeout(10000);
                conn.setConnectTimeout(15000);

                conn.connect();

                paramsString = sbParams.toString();

                wr = new DataOutputStream(conn.getOutputStream());
                wr.writeBytes(paramsString);
                wr.flush();
                wr.close();

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        else if(method.equals("GET")){
            // request method is GET

            if (sbParams.length() != 0) {
                url += "?" + sbParams.toString();
            }

            try {
                urlObj = new URL(url);

                conn = (HttpURLConnection) urlObj.openConnection();

                conn.setDoOutput(false);

                conn.setRequestMethod("GET");

                conn.setRequestProperty("Accept-Charset", charset);

                conn.setConnectTimeout(15000);

                conn.connect();

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

        }

        try {
            //Receive the response from the server
            InputStream in = new BufferedInputStream(conn.getInputStream());
            BufferedReader reader = new BufferedReader(new InputStreamReader(in));

            String line;
            while ((line = reader.readLine()) != null) {
                result.append(line);
            }

            Log.d("JSON Parser", "result: " + result.toString());

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

        conn.disconnect();

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

        // return JSON Object
        return jObj;
    }}

AsyncTask

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

        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            mView=new CatLoadingView();
            mView.show(getSupportFragmentManager(),"");
        }
        protected String doInBackground(String... args) {
            int success;
            String name = inputName.getText().toString();
            String password = inputPassword.getText().toString();
            try {
                // Building Parameters
                HashMap<String,String> h1=new HashMap<>();
                h1.put("username", name);
                h1.put("password", password);
                // getting JSON Object
                //url accepts POST method
                JSONObject json= jsonParser.makeHttpRequest(api_url,"POST", h1);
                // check log cat from response
                Log.e("Create Response 1", json.toString());
                JsonData=json.toString();
                JSONObject reader=new JSONObject(JsonData);
                JSONObject jobj=reader.getJSONObject("user");
                Log.e("Create Response 2", jobj.toString());
                    JSONObject jobj2 = jobj.getJSONObject("data");
                    String user_id = jobj2.getString("USER_NAME");
                    //String bimage=jobj2.getString("DISPLAY_PIC");
                    Intent intent = new Intent(getBaseContext(), MainActivity.class);
                    intent.putExtra("id", user_id);
                    // intent.putExtra("image",bimage);
                    startActivity(intent);
            } catch (JSONException e) {
                e.printStackTrace();

            }
            // check for success tag
            return null;
        }
        /**
         * After completing background task Dismiss the progress dialog
         * **/
        protected void onPostExecute(String file_url) {
            // dismiss the dialog once done
            mView.dismiss();


        }

1:当我输入正确的登录凭据时,登录将成功,并且

JSON结果是

{"user":{"data":{"USER_ID":"1","USER_NAME":"Vaisakh CV","BRANCH_ID":"1"}}} .

2:但是当我输入错误的凭据时,JSON结果是

{"user":{"error":"Invalid data!"}}

3 :我的问题是在错误尝试后输入正确的凭据后 JSON 结果是

{"user":{"error":"Invalid data!"}}{"user":{"data":{"USER_ID":"1","USER_NAME":"Vaisakh CV","BRANCH_ID":"1"}}}

我只需要

{"user":{"data":{"USER_ID":"1","USER_NAME":"Vaisakh CV","BRANCH_ID":"1"}}}

如何解决这个问题?提前致谢!

要解析数据,您必须先检查密钥是否存在。使用 has 方法检查键 "data" 和 "error" 是否存在。如果响应有键 "error" 你应该显示一条错误消息。如果响应有键 "data",您可以解析它并显示数据。

JSONObject reader = new JSONObject(JsonData);
JSONObject jobj = reader.getJSONObject("user");
if(jobj.has("data")) {
    // parse data
} else if(jobj.has("error")) {
    // raise error
}

关于 JSON 加起来的第二个问题,

您已经创建了一个 StringBuilder 作为全局。所以当你再次请求时,它会被串联起来。为防止这种情况,请清除 StringBuilder 或按如下方式再次初始化它。

result = new StringBuilder(); // add this line
String line;
while ((line = reader.readLine()) != null) {
    result.append(line);
}

你可以使用

jsonobject.optString("key");

oppString 仅在 jsonobject 具有相同键时执行。 它永远不会崩溃。

如果您自定义它,您可以获得解决方案,但实际问题是服务器 side.Server 没有以正确的方式返回数据。当您输入正确的凭据时,我会给出什么回应。

{"status":"true","user":{"data":{"USER_ID":"1","USER_NAME":"Vaisakh CV","BRANCH_ID":"1"}}} .

当您输入错误的凭据时,响应必须是。

{"status":"false"}.

这将是您解析服务的更好选择

或者你可以这样解析。如果您在 catch 块中输入,则意味着您输入了错误的凭据,否则您输入正确

try {
            JSONObject jsonObject = new JSONObject("response");
            JSONObject user = jsonObject.getJSONObject("user");
            JSONObject data = user.getJSONObject("data");
            String userId = data.getString("USER_ID");
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(this, "Wrong Credentials", Toast.LENGTH_LONG).show();
        }