Creating a simple JSON object

suggest change

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:

{  
   "name":"test",
   "content":"Hello World!!!1",
   "year":2016,
   "value":3.23,
   "member":true,
   "null_value":null
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


JSON handling with org.json:
*Creating a simple JSON object

Table Of Contents
6JSON handling with org.json
169XMPP
230AIDL
242Okio