How do I parse JSON in Android? [duplicate]

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP


How do I parse JSON in Android? [duplicate]



This question already has an answer here:



How do I parse a JSON feed in Android?



This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.





Dont know about Android, but under normal Java I use this: code.google.com/p/google-gson EDIT: Does work under android: javacodegeeks.com/2011/01/…
– James Bennet
Mar 7 '12 at 17:00





there is a json parser embedded in the sdk. see developer.android.com/reference/org/json/package-summary.html
– njzk2
Mar 7 '12 at 17:01





stackoverflow.com/a/2840873/643350
– Dipin
Mar 7 '12 at 17:05





You can have look at below link where you get data using retrofit. tatnorix.in/how-to-get-json-data-using-get-retrofit-in-android
– Tatson Baptista
Jul 17 at 8:08




3 Answers
3



Note: this answer has not been updated since 2013. The suggested way to download the json is not recommended for android anymore as the http client has been removed from the sdk as of api 23.
However, the parsing logic below still applies



Android has all the tools you need to parse json built-in. Example follows, no need for GSON or anything like that.



Get your JSON:


DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost(http://someJSONUrl/jsonWebService);
// Depends on your web service
httppost.setHeader("Content-type", "application/json");

InputStream inputStream = null;
String result = null;
try {
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();

inputStream = entity.getContent();
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();

String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "n");
}
result = sb.toString();
} catch (Exception e) {
// Oops
}
finally {
try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
}



now you have your JSON, so what?



Create a JSONObject:


JSONObject jObject = new JSONObject(result);



To get a specific string


String aJsonString = jObject.getString("STRINGNAME");



To get a specific boolean


boolean aJsonBoolean = jObject.getBoolean("BOOLEANNAME");



To get a specific integer


int aJsonInteger = jObject.getInt("INTEGERNAME");



To get a specific long


long aJsonLong = jObject.getLong("LONGNAME");



To get a specific double


double aJsonDouble = jObject.getDouble("DOUBLENAME");



To get a specific JSONArray:


JSONArray jArray = jObject.getJSONArray("ARRAYNAME");



To get the items from the array


for (int i=0; i < jArray.length(); i++)
{
try {
JSONObject oneObject = jArray.getJSONObject(i);
// Pulling items from the array
String oneObjectsItem = oneObject.getString("STRINGNAMEinTHEarray");
String oneObjectsItem2 = oneObject.getString("anotherSTRINGNAMEINtheARRAY");
} catch (JSONException e) {
// Oops
}
}





There also could be a case when you receive an JSONArray and if you try to JSONObject jObject = new JSONObject(result) - you'll get an exeption about parsing. In such case JSONArray jArray = new JSONArray(result) would work.
– Stan
Feb 18 '13 at 19:33



Writing JSON Parser Class


public class JSONParser {

static InputStream is = null;
static JSONObject jObj = null;
static String json = "";

// constructor
public JSONParser() {}

public JSONObject getJSONFromUrl(String url) {

// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);

HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();

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

try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}

// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}

// return JSON String
return jObj;

}
}



Parsing JSON Data
Once you created parser class next thing is to know how to use that class. Below i am explaining how to parse the json (taken in this example) using the parser class.



2.1. Store all these node names in variables: In the contacts json we have items like name, email, address, gender and phone numbers. So first thing is to store all these node names in variables. Open your main activity class and declare store all node names in static variables.


// url to make request
private static String url = "http://api.9android.net/contacts";

// JSON Node names
private static final String TAG_CONTACTS = "contacts";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_EMAIL = "email";
private static final String TAG_ADDRESS = "address";
private static final String TAG_GENDER = "gender";
private static final String TAG_PHONE = "phone";
private static final String TAG_PHONE_MOBILE = "mobile";
private static final String TAG_PHONE_HOME = "home";
private static final String TAG_PHONE_OFFICE = "office";

// contacts JSONArray
JSONArray contacts = null;



2.2. Use parser class to get JSONObject and looping through each json item. Below i am creating an instance of JSONParser class and using for loop i am looping through each json item and finally storing each json data in variable.


// Creating JSON Parser instance
JSONParser jParser = new JSONParser();

// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);

try {
// Getting Array of Contacts
contacts = json.getJSONArray(TAG_CONTACTS);

// looping through All Contacts
for(int i = 0; i < contacts.length(); i++){
JSONObject c = contacts.getJSONObject(i);

// Storing each json item in variable
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String email = c.getString(TAG_EMAIL);
String address = c.getString(TAG_ADDRESS);
String gender = c.getString(TAG_GENDER);

// Phone number is agin JSON Object
JSONObject phone = c.getJSONObject(TAG_PHONE);
String mobile = phone.getString(TAG_PHONE_MOBILE);
String home = phone.getString(TAG_PHONE_HOME);
String office = phone.getString(TAG_PHONE_OFFICE);

}
} catch (JSONException e) {
e.printStackTrace();
}





This answer somewhat skips over downloading the JSON off of the main thread
– cricket_007
Jul 8 at 14:00



I've coded up a simple example for you and annotated the source. The example shows how to grab live json and parse into a JSONObject for detail extraction:


try{
// Create a new HTTP Client
DefaultHttpClient defaultClient = new DefaultHttpClient();
// Setup the get request
HttpGet httpGetRequest = new HttpGet("http://example.json");

// Execute the request in the client
HttpResponse httpResponse = defaultClient.execute(httpGetRequest);
// Grab the response
BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8"));
String json = reader.readLine();

// Instantiate a JSON object from the request response
JSONObject jsonObject = new JSONObject(json);

} catch(Exception e){
// In your production code handle any errors and catch the individual exceptions
e.printStackTrace();
}



Once you have your JSONObject refer to the SDK for details on how to extract the data you require.





Hi i have put this in but getting errors i have imported everything but still getting problems
– iamlukeyb
Mar 7 '12 at 17:18





You will need to wrap the code block above in a try-catch, I've edited the code to reflect this.
– Ljdawson
Mar 7 '12 at 17:22





Still having problems?
– Ljdawson
Mar 7 '12 at 17:36





if the file retrieved has newline characters, the readLine() fails.
– dpp
Jun 3 '13 at 6:53


readLine()




Thank you for your interest in this question.
Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).


Would you like to answer one of these unanswered questions instead?

Popular posts from this blog

Arduino Mega cannot recieve any sketches, stk500_recv() programmer is not responding

Visual Studio Code: How to configure includePath for better IntelliSense results

C++ virtual function: Base class function is called instead of derived