NOW Hiring

Quick links

Share

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.

Alternatively you can use existing Open Source libraries like GSON or Moshi for your JSON processing.

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) {
                e.printStackTrace();
        }
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) {
                e.printStackTrace();
        }
        System.out.println(object);
}

2. About this website

Moshi Homepage === vogella GmbH training and consulting support

TRAINING SERVICE & SUPPORT

The vogella company provides comprehensive training and education services from experts in the areas of Eclipse RCP, Android, Git, Java, Gradle and Spring. We offer both public and inhouse training. Whichever course you decide to take, you are guaranteed to experience what many before you refer to as “The best IT class I have ever attended”.

The vogella company offers expert consulting services, development support and coaching. Our customers range from Fortune 100 corporations to individual developers.

Copyright © 2012-2016 vogella GmbH. Free use of the software examples is granted under the terms of the EPL License. This tutorial is published under the Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Germany license.

See Licence.