Creating a simple JSON object

Download android eBook


Create the JSONObject using the empty constructor and add fields using the put() method, which is overloaded so that it can be used with different types:

try {
    // Create a new instance of a JSONObject
    final JSONObject object = new JSONObject();
    // With put you can add a name/value pair to the JSONObject
    object.put("name", "test");
    object.put("content", "Hello World!!!1");
    object.put("year", 2016);
    object.put("value", 3.23);
    object.put("member", true);
    object.put("null_value", JSONObject.NULL);

    // Calling toString() on the JSONObject returns the JSON in string format.
    final String json = object.toString();
} catch (JSONException e) {
    Log.e(TAG, "Failed to create JSONObject", e);

The resulting JSON string looks like this:

   "content":"Hello World!!!1",


Contributors: 13
Licensed under: CC-BY-SA

Not affiliated with Stack Overflow
Rip Tutorial:

Download eBook