Lakshman Pilaka
Lakshman Pilaka

Reputation: 1951

Parsing JSON response from web api in Android

i get a response from web api in the following format

{
    "userId": "7c29a313-40ab-4927-bc43-7fc8518fe247",
    "userName": "[email protected]",
    "email": "[email protected]",
    "mobileNumber": null,
    "redirectTo": "none"
}

I try to parse it with following code

tvUserName.setText(new JSONObject(response).get("userName").toString());

but i get the following error

Value {"userId":"7c29a313-40ab-4927-bc43-7fc8518fe247","userName":"[email protected]","email":"[email protected]","mobileNumber":null,"redirectTo":"none"} of type java.lang.String cannot be converted to JSONObject

i can't find any mistake in the json file format, but still why do i get this error?

the async task is as follows

class authenticateLogin extends AsyncTask<Void, Void, String> {

    private ProgressBar progressBar;

    private Exception exception;

    protected void onPreExecute() {
        progressBar = (ProgressBar) findViewById(R.id.progressBar);
        progressBar.setVisibility(View.VISIBLE);
        //responseView.setText("");
    }

    protected String doInBackground(Void... urls) {

        String result = "Error has occured";

        try {
            URL url;
            URLConnection urlConn;

            url = new URL(API_URL);
            urlConn = url.openConnection();
            urlConn.setDoInput(true);
            urlConn.setDoOutput(true);
            urlConn.setUseCaches(false);
            urlConn.setRequestProperty("Content-Type", "application/json");
            urlConn.setRequestProperty("Host", "api_app.azurewebsites.net");
            urlConn.connect();

            JSONObject jsonParam = new JSONObject();
            jsonParam.put("loginid", "login");
            jsonParam.put("password", "pass");

            PrintWriter out = new PrintWriter(urlConn.getOutputStream());
            out.print(jsonParam);
            out.close();

            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
            StringBuilder stringBuilder = new StringBuilder();
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                stringBuilder.append(line).append("\n");
            }
                bufferedReader.close();
                result = stringBuilder.toString();

        }
        catch (java.io.IOException ex)
        {
            result = "IO-Error: "  + ex.getMessage();
            Log.e("IO Error Tag",ex.getStackTrace().toString());
        }
        catch (org.json.JSONException ex)
        {
            result = "JSON-Error: "  + ex.getMessage();
        }

        return result;
    }

    protected void onPostExecute(String response) {
        if(response == null) {
            response = "THERE WAS AN ERROR";
        }
        progressBar.setVisibility(View.GONE);
        Log.i("INFO", response);
        //responseView.setText(response);
    }
}

Upvotes: 0

Views: 2199

Answers (2)

Arpit Patel
Arpit Patel

Reputation: 8067

Create JsonParser.java And just copy-paste this code

JsonParser.java

package info.tranetech.laundry.adapter;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;

public class JSONParser {
    static String response = null;
    public final static int GET = 1;
    public final static int POST = 2;

    public JSONParser() {

    }

    /**
     * Making service call
     * @url - url to make request
     * @method - http request method
     * */
    public String makeServiceCall(String url, int method) {
        return this.makeServiceCall(url, method, null);
    }

    /**
     * Making service call
     * @url - url to make request
     * @method - http request method
     * @params - http request params
     * */
    public String makeServiceCall(String url, int method,
            List<NameValuePair> params) {
        try {
            // http client
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpEntity httpEntity = null;
            HttpResponse httpResponse = null;

            // Checking http request method type
            if (method == POST) {
                HttpPost httpPost = new HttpPost(url);
                // adding post params
                if (params != null) {
                    httpPost.setEntity(new UrlEncodedFormEntity(params));
                }

                httpResponse = httpClient.execute(httpPost);

            } else if (method == GET) {
                // appending params to url
                if (params != null) {
                    String paramString = URLEncodedUtils
                            .format(params, "utf-8");
                    url += "?" + paramString;
                }
                HttpGet httpGet = new HttpGet(url);

                httpResponse = httpClient.execute(httpGet);

            }
            httpEntity = httpResponse.getEntity();
            response = EntityUtils.toString(httpEntity);

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

        return response;

    }
}

And call in doInBackground like this

  @Override
        protected Void doInBackground(Void... arg0) {
            // Creating service handler class instance
            JSONParser JP = new JSONParser();

            // Making a request to url and getting response
            String jsonStr = JP.makeServiceCall("http://.com/mis/Laundry/men_dry.php", JSONParser.GET);

            Log.d("Response: ", "> " + jsonStr);

            if (jsonStr != null) {
                try {


                    JSONObject jsonObj = new JSONObject(jsonStr);

                   String A = jsonObj.getString("userId").toString();   

                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else {
                Log.e("ServiceHandler", "Couldn't get any data from the url");
            }

            return null;
        }

Upvotes: 0

You should use instead:

tvUserName.setText(new JSONObject(response).getString("userName"));

Upvotes: 1

Related Questions