Home Tutorials Training Consulting Books Company Contact us

Get more...

Training Events

JSON with Android. This article describes how to process JSON within Android.

1. Android and JSON

1.1. Included standard library

The Android platform includes the json.org library which allows processing and creating JSON files.

Prefer using open source libraries like Gson or https://github.com/square/moshi[Moshi for JSON processing. These libraries are easier to use, faster and provide more flexibility

1.2. Example: Reading JSON

Converting a JSON string into a JSON object is also simple. Create the following coding for the activity.

import org.json.JSONArray;
import org.json.JSONObject;

String jsonString = readJsonObjectFromSomeWhere(); (1)
try {
    JSONObject json = new JSONObject(jsonString);
    } catch (Exception e) {
1 method which provides a JSON string, left out for brevity

The code example cannot run in the main thread in Android. Ensure to run this snippet outside the main thread.

1.3. Write JSON

Writing JSON is very simple. Just create the JSONObject or JSONArray and use the toString() method.

public void writeJSON() {
    JSONObject object = new JSONObject();
    try {
        object.put("name", "Jack Hack");
        object.put("score", new Integer(200));
        object.put("current", new Double(152.32));
        object.put("nickname", "Hacker");
    } catch (JSONException e) {
Legal Privacy Policy Change consent