Hoe parseer ik een JSON-feed in Android?
Antwoord 1, autoriteit 100%
Android heeft alle tools die je nodig hebt om json te ontleden ingebouwd. Voorbeeld volgt, geen GSON of iets dergelijks nodig.
Ontvang uw JSON:
Stel dat je een json-tekenreeks hebt
String result = "{\"someKey\":\"someValue\"}";
Maak een JSONObject:
JSONObject jObject = new JSONObject(result);
Als uw json-tekenreeks een array is, bijvoorbeeld:
String result = "[{\"someKey\":\"someValue\"}]"
dan moet u JSONArray
gebruiken zoals hieronder wordt aangetoond en niet JSONObject
Om een specifieke tekenreeks te krijgen
String aJsonString = jObject.getString("STRINGNAME");
Om een specifieke boolean te krijgen
boolean aJsonBoolean = jObject.getBoolean("BOOLEANNAME");
Om een specifiek geheel getal te krijgen
int aJsonInteger = jObject.getInt("INTEGERNAME");
Om een specifieke long te krijgen
long aJsonLong = jObject.getLong("LONGNAME");
Om een specifiek dubbel te krijgen
double aJsonDouble = jObject.getDouble("DOUBLENAME");
Om een specifieke JSONArrayte krijgen:
JSONArray jArray = jObject.getJSONArray("ARRAYNAME");
De items uit de array halen
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
}
}
Antwoord 2, autoriteit 8%
-
JSON-parserklasse schrijven
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
Zodra u Parser-klasse hebt gemaakt, is het volgende om te weten hoe u die klasse kunt gebruiken. Hieronder leg ik uit hoe je de JSON (genomen in dit voorbeeld) kunt ontleden met behulp van de parser-klasse.2.1. Bewaar al deze knooppuntnamen in variabelen: in de contacten, JSON hebben we items zoals naam, e-mail, adres, gender en telefoonnummers. Dus het eerste is om al deze knooppuntnamen in variabelen op te slaan. Open uw hoofdactiviteitenklasse en verklaar alle knooppuntnamen in statische variabelen.
// 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. Gebruik Parser-klasse om
JSONObject
te krijgen en door elk JSON-item loopt. Hieronder maak ik een exemplaar vanJSONParser
CLASSE en gebruik voor lus Ik loop door elk JSON-item en opslaat eindelijk elke JSON-gegevens in variabele.// 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(); }
Antwoord 3, Autoriteit 6%
Ik heb een eenvoudig voorbeeld voor u gecodeerd en de bron geannoteerd. Het voorbeeld laat zien hoe je Live JSON kunt pakken en parseren in een JSONObject
voor detailwinning:
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();
}
Zodra u uw JSONObject
heeft, raadpleegt u de SDK voor details over hoe u de benodigde gegevens kunt extraheren.