O'Reilly logo

JavaScript JSON Cookbook by Ray Rischpater

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required