JSON Parsing Error (Appending Results)

416 views Asked by At

This is My JSON Parser 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 : When I enter correct Login credentials Login will Successful, and the

JSONResult is

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

2 : But when i enter wrong Credentials the JSONResult is

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

3 : and my problem is after entering correct credentials after wrong attempt the JSONResult is

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

i need only

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

How to resolve this? thanks in advance!

3

There are 3 answers

1
Neerajlal K On BEST ANSWER

For parsing the data you have to check if the key exists first. Use has method to check if the keys "data" and "error" exists. If the response has key "error" you should show an error message. If the response has key "data" you can parse it and show the data.

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

For your second problem of the JSON getting added up,

You have a created a StringBuilder as global. So when you request again, it will be concatenated. To prevent this clear the StringBuilder or initialize it again as follows.

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

you can use

jsonobject.optString("key");

oppString only perform when jsonobject having same key. it will never crash.

0
SANJAY GUPTA On

If you customize this you can get the solution but actual problem is from server side.Server is not returning the data in proper way. I am giving what should the response when you enter right credentials.

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

When you enter wrong credential the response must be.

{"status":"false"}.

This would be the better option for you to parse a service

Or you can parse like this. If you enter in catch block that means you entered wrong credentials else you entered right

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