9

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?

Willi Mentzel
  • 27,862
  • 20
  • 113
  • 121
David Brown
  • 4,783
  • 17
  • 50
  • 75

5 Answers5

19

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...........

dfetter88
  • 5,381
  • 13
  • 44
  • 55
viv
  • 6,158
  • 6
  • 39
  • 54
3

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());
    }
Octavian Helm
  • 39,405
  • 19
  • 98
  • 102
Ian G. Clifton
  • 9,349
  • 2
  • 33
  • 34
3

You can also check out Google's GSON library here. The GSON user guide here has some useful examples to help get you started. I've found GSON to be simple and powerful.

Jedidiah Thomet
  • 401
  • 3
  • 12
1

You can use the org.json package, bundled in the SDK.

See here: http://developer.android.com/reference/org/json/JSONTokener.html

adamk
  • 45,184
  • 7
  • 50
  • 57
1

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.

StaxMan
  • 113,358
  • 34
  • 211
  • 239