Generating JSON on Android

JSONObject also supports setter methods to initialize data in a JSON map. With these methods, you can assign data to a JSON object and then get the JSON representation by invoking its toString method.

How to do it…

Here's a simple example:

import org.JSON.JSONObject;

JSONObject data = new JSONObject();
data.put("call", "kf6gpe-7");
data.put("lat", 37.40150);
data.put("lng", -122.03683);
String json = data.toString();

How it works…

The polymorphic put method can take an integer, long integer, object, Boolean, or double, assigning the slot you name the value you specify.

The JSONObject class defines the toString method, which takes an optional number of spaces to indent nested structures for pretty-printed JSON. If you don't ...

Get JavaScript JSON Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.