0

I am trying to parse json but unable to get. Can anybody help me to find out how to to get this:

{
  "firstName": "****",
  "headline": "Software Engineer",
  "id": "Y8gyiQS0gM",
  "lastName": "****",
  "location": {
    "country": {"code": "in"},
    "name": "Bengaluru Area, India"
  },
  "pictureUrl": "",
  "siteStandardProfileRequest": {"url": ""}
}

I used this code to get but didn't get any result in log.

DefaultHttpClient httpclient = new DefaultHttpClient();
try {
    HttpGet httpget = new HttpGet("url");

    HttpResponse response = httpclient.execute(httpget);
    String jsonResp=EntityUtils.toString(response.getEntity());
    Log.d("HTTP","Rsponse : "+ jsonResp);

    JSONObject jsonObject = new JSONObject(jsonResp);
    String firstname = jsonObject.getString("firstName");
    String id = jsonObject.getString("id");
    String headline = jsonObject.getString("headline");
    String lastName = jsonObject.getString("lastName");
    //String pictureUrl  = jsonObject2.getString("pictureUrl");

    Log.d("HTTP", "firstname : " + firstname.toString() + "id" + id.toString());
} ...

I have wrote this code to view the user profile. But didn't get anything as result.

EDIT:

public class ViewProfileActivity extends ListActivity {

Button userProfile;
TextView tv;
private static final String TAG_ID = "id";
private static final String TAG_FNAME = "firstname";
private static final String TAG_LNAME = "lastname";
private static final String TAG_HLINE = "headline";
private static final String TAG_PURL = "pictureUrl";
private static final String TAG_URL = "url";
private ProgressDialog pDialog;
ArrayList<HashMap<String, String>> contactList = null;
 String url="...."

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.view_user);

    userProfile = (Button) findViewById(R.id.view);
    tv=(TextView)findViewById(R.id.textView1);

    userProfile.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View arg0) {
            new GetContacts().execute();
        }


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

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                // Showing progress dialog
                pDialog = new ProgressDialog(ViewProfileActivity.this);
                pDialog.setMessage("Please wait...");
                pDialog.setCancelable(false);
                pDialog.show();

            }

            @Override
            protected Void doInBackground(Void... params) {
                DefaultHttpClient httpclient = new DefaultHttpClient();
                try {
                    HttpGet httpget = new HttpGet(
                            "url");
                    HttpResponse response = httpclient.execute(httpget);
                    String jsonResp = EntityUtils.toString(response.getEntity());
                    Log.d("HTTP","Rsponse : "+ jsonResp);

                    JSONObject jsonObject = new JSONObject(jsonResp);
                    String firstname = jsonObject.getString("firstName");
                    String id = jsonObject.getString("id");
                    String headline = jsonObject.getString("headline");
                    String lastname = jsonObject.getString("lastName");
                    String pictureUrl = jsonObject.getString("pictureUrl");
                    JSONObject jsonObject2 = jsonObject
                            .getJSONObject("siteStandardProfileRequest");
                    String url = jsonObject2.getString("url");
                    Log.d("HTTP", "firstname : " + firstname + "\n" + "id :"
                            + id + "\n" + "headline : " + headline + "\n"
                            + "lastName :" + lastname + "\n" + "pictureUrl :"
                            + pictureUrl + "\n" + "Url :" + url);


                    HashMap<String, String> contact = new HashMap<String, String>();
                    contact.put(TAG_ID, id);
                    contact.put(TAG_FNAME, firstname);
                    contact.put(TAG_LNAME, lastname);
                    contact.put(TAG_HLINE, headline);
                    contact.put(TAG_PURL, pictureUrl);
                    contact.put(TAG_URL, url);
                    contactList.add(contact);
                    tv.setText((CharSequence) contactList);

                } catch (Exception e) {
                    e.printStackTrace();
                }
                return null;
            }

            @Override
            protected void onPostExecute(Void result) {
                super.onPostExecute(result);
                // Dismiss the progress dialog
                if (pDialog.isShowing())
                    pDialog.dismiss();

                ListAdapter adapter = new SimpleAdapter(
                        LinkedInSampleActivity.this, contactList,
                        R.layout.list_item, new String[] {TAG_URL,TAG_FNAME}, new int[]{R.id.imageView1,R.id.textView1 });
                setListAdapter(adapter);
            }
        }

});
}

}

user3886658
  • 53
  • 1
  • 7

2 Answers2

0

For Parsing:
If you reach till Log.d("HTTP","Rsponse : "+ jsonResp);, you can use Gson for parsing.

public class JsonResponseModel {

 String firstName;  
 String lastName;  
 String headline;  
 String id;  
//rest of the fields

//getters setters functions

}

For Naming discrepancies(according to the variables in webservice) in the model class, can use annotations like @SerializedName.

Then, using it with Gson:

Gson gson = new Gson();
JsonResponseModel responseModelObject = new JsonResponseModel();
responseModelObject= gson.fromJson(jsonResp, JsonResponseModel.class);   
//now you have the data in responseModelObject

NetworkOnMainThreadException:
Why i write "If" you reach...in the first line of the answer.

With the code posted in the question, you may calling the network operation directly(?), you might face that exception.

Community
  • 1
  • 1
Pararth
  • 8,114
  • 4
  • 34
  • 51
0

Use this code to make HTTP request (for the url pass in your url)

HttpParams params = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(params, 500);

Client = new DefaultHttpClient(params);
httpget = new HttpGet(url);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
mContent = Client.execute(httpget, responseHandler);

Then use this to get your data:

JSONObject jsonObject = new JSONObject(mContent);
String firstname = jsonObject.getString("firstName");
String id = jsonObject.getString("id");
String headline = jsonObject.getString("headline");
String lastName = jsonObject.getString("lastName");

Note::

  • for the url you have to pass your url from which you are trying to get the JSON response
  • Also place the above code inside an Asynchronous task otherwise it crashes because since you are making a network request

Hope this helps! Revert back if you have any errors.

{EDIT}

public class ViewProfileActivity extends ListActivity {

    Button userProfile;
    TextView tv;
    private static final String TAG_ID = "id";
    private static final String TAG_FNAME = "firstname";
    private static final String TAG_LNAME = "lastname";
    private static final String TAG_HLINE = "headline";
    private static final String TAG_PURL = "pictureUrl";
    private static final String TAG_URL = "url";
    private ProgressDialog pDialog;
    ArrayList<HashMap<String, String>> contactList = null;
     String url="...."

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.view_user);

        userProfile = (Button) findViewById(R.id.view);
        tv=(TextView)findViewById(R.id.textView1);

        userProfile.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                new GetContacts().execute();
            }


            class GetContacts extends AsyncTask<Void, String, Void> {
                String firstname;
                String id;
                String headline;
                String lastname;
                String pictureUrl;

                @Override
                protected void onPreExecute() {
                    super.onPreExecute();
                    // Showing progress dialog
                    pDialog = new ProgressDialog(ViewProfileActivity.this);
                    pDialog.setMessage("Please wait...");
                    pDialog.setCancelable(false);
                    pDialog.show();

                }

                @Override
                protected Void doInBackground(Void... params) {
                    DefaultHttpClient httpclient = new DefaultHttpClient();
                    try {
                        HttpGet httpget = new HttpGet(
                                "url");
                        HttpResponse response = httpclient.execute(httpget);
                        String jsonResp = EntityUtils.toString(response.getEntity());
                        Log.d("HTTP","Rsponse : "+ jsonResp);

                        JSONObject jsonObject = new JSONObject(jsonResp);
                        firstname = jsonObject.getString("firstName");
                        id = jsonObject.getString("id");
                        headline = jsonObject.getString("headline");
                        lastname = jsonObject.getString("lastName");
                        pictureUrl = jsonObject.getString("pictureUrl");
                        JSONObject jsonObject2 = jsonObject
                                .getJSONObject("siteStandardProfileRequest");
                        String url = jsonObject2.getString("url");
                        Log.d("HTTP", "firstname : " + firstname + "\n" + "id :"
                                + id + "\n" + "headline : " + headline + "\n"
                                + "lastName :" + lastname + "\n" + "pictureUrl :"
                                + pictureUrl + "\n" + "Url :" + url);


                        HashMap<String, String> contact = new HashMap<String, String>();
                        contact.put(TAG_ID, id);
                        contact.put(TAG_FNAME, firstname);
                        contact.put(TAG_LNAME, lastname);
                        contact.put(TAG_HLINE, headline);
                        contact.put(TAG_PURL, pictureUrl);
                        contact.put(TAG_URL, url);
                        contactList.add(contact);
                        tv.setText((CharSequence) contactList);

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    return null;
                }

                @Override
                protected void onPostExecute(Void result) {
                    super.onPostExecute(result);
                    // Dismiss the progress dialog
                    if (pDialog.isShowing())
                        pDialog.dismiss();

                    ListAdapter adapter = new SimpleAdapter(
                            LinkedInSampleActivity.this, contactList,
                            R.layout.list_item, new String[] {TAG_URL,TAG_FNAME}, new int[]{R.id.imageView1,R.id.textView1 });
                    setListAdapter(adapter);

                    // SET your Text Views here 
                    //
                    //USE the variables stored globally in your Aynnc Class
                    //
                    //
                }
            }

    });
    }
}
Devrath
  • 42,072
  • 54
  • 195
  • 297
  • yes. I got the result. But I want to display in activity. So how can I do that? – user3886658 Jul 30 '14 at 04:39
  • @user3886658 .... If you have this code in `Async task` of the `doInbackground` ..... you need to display the results in `onPublish` or `onPostExecute` .... since the UI tasks must not be performed in `doInBackground` ! – Devrath Jul 30 '14 at 04:50
  • Can you please explain how to do @Devrath – user3886658 Jul 30 '14 at 05:24
  • If you are new to android ! ..... learn some tutorials on how to work with asynctask, its really simple .... Post a new Question ! with new requirements! – Devrath Jul 30 '14 at 05:32
  • I saw the new Edit .... wrong thing you are doing is .... you are trying to set text view in 'doInBackground' .... another simple solution is declare string variables globally and set the textviews in `onPostExecute` .... Hope that helps ! – Devrath Jul 30 '14 at 05:35
  • I have done the above edit. But i got NullPointerException @Devrath – user3886658 Jul 30 '14 at 11:32
  • @user3886658 ..... Check the edit ... Hope it helps !... U think you get the idea from my answer ! – Devrath Jul 30 '14 at 15:28