JSON解析错误(附加结果)

时间:2017-01-06 08:53:34

标签: android json web-services login android-json

这是我的JSON解析器类

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:当我输入正确的登录凭据时,登录将成功,

JSONResult

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

2:但是当我输入错误的凭证时,JSONResult就是

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

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

{"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"}}}

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

3 个答案:

答案 0 :(得分:0)

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

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

答案 1 :(得分:0)

你可以使用

jsonobject.optString("key");

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

答案 2 :(得分:0)

如果您自定义这个,您可以获得解决方案,但实际问题来自服务器端.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();
        }