How To Parse Api Response In Android?
How can we parse the response in android? API response is {'id':29,'name':'demo','email':'demo@gmail.com'} How can i get the value of id,name and email. AsyncHttpClient client =
Solution 1:
Replace your code like this, This is how you need to parse if you have more than on object, then you have to use the loop.
AsyncHttpClient client = newAsyncHttpClient();
client.get("http://XXX.XX.X.XXX/api/api.php?apicall=login", params, newTextHttpResponseHandler() {
@OverridepublicvoidonSuccess(int statusCode, Header[] headers, String response) {
prgDialog.hide();
Toast.makeText(getApplicationContext(), response, Toast.LENGTH_LONG).show();
try {
JSONObject reader = newJSONObject(response);
int id = reader.getInt("id");
String name = reader.getString("name");
String email = reader.getString("email");
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}
}
});
Solution 2:
try this:
Thread thread = newThread(newRunnable() {
@Overridepublicvoidrun() {
try {
String mainUrl = "http://YOUR_ADRESS";
StringBuilder sbPostData = newStringBuilder(mainUrl);
mainUrl = sbPostData.toString();
try {
//prepare connectionURL myURL = newURL(mainUrl);
URLConnection myURLConnection = myURL.openConnection();
myURLConnection.connect();
BufferedReader reader = newBufferedReader(newInputStreamReader(myURLConnection.getInputStream()));
//reading responseString response;
response = reader.readLine();
JSONArray jsonarray = newJSONArray(response);
JSONObject jsonobject0 = jsonarray.getJSONObject(0);
JSONObject jsonobject0 = jsonarray.getJSONObject(0);
//getting the email and save it in EMAIL string//you can do the other parts like this. its easy StringEMAIL = jsonobject0.getString("email");
while ((response = reader.readLine()) != null)
//print responseLog.d("RESPONSE", ""+response);
//finally close connection
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
thread.start();
Post a Comment for "How To Parse Api Response In Android?"