I have searched alot on JSON Parsing in Android, but couldn't quite convinced. Actually got a brief idea but not so clear yet regarding JSON Parsing.
How to implement the JSON Parsing in the Application?
This is a very simple JSON String
{"key1":"value1","key2":"value2"} In order to get values for it use JSONObject like this :
JSONObject json_obj=new JSONObject(your json string); String value1=json_obj.getString("key1"); String value2=json_obj.getString("key2"); This is a slightly complex json string
[{"key1":"value1","key2":"value2"},{"key1":"value1","key2":"value2"}] In order to extract values from this use JSONArray
JSONArray jArray=new JSONArray(your json string); for(int i=0;i<(jArray.length());i++) { JSONObject json_obj=jArray.getJSONObject(i); String value1=json_obj.getString("key1"); String value2=json_obj.getString("key2"); } Hope this helps a bit...........
See: http://developer.android.com/reference/org/json/package-summary.html
Primarily, you'll be working with JSONArray and JSONObject.
Simple example:
try { JSONObject json = new JSONObject(jsonString); int someInt = json.getInt("someInt"); String someString = json.getString("someString"); } catch (JSONException e) { Log.d(TAG, "Failed to load from JSON: " + e.getMessage()); } You can use the org.json package, bundled in the SDK.
See here: http://developer.android.com/reference/org/json/JSONTokener.html
One more choice: use Jackson.
Simple usage; if you have a POJO to bind to:
ObjectMapper mapper = new ObjectMapper(); // reusable MyClass value = mapper.readValue(source, MyClass.class); // source can be String, File, InputStream // back to JSON: String jsonString = mapper.writeValue(value); to a Map:
Map<?,?> map = mapper.readValue(source, Map.class); or to a Tree: (similar to what default Android org.json package provides)
JsonNode treeRoot = mapper.readTree(source); and more examples can be found at http://wiki.fasterxml.com/JacksonInFiveMinutes.
Benefits compared to other packages is that it is lightning fast; very flexible and versatile (POJOs, maps/lists, json trees, even streaming parser), and is actively developed.