Working with JSONObject - xmljim/JSON-JEP GitHub Wiki
The JSONObject
interface contains numerous methods for setting and getting values.
Setting values
There are several put(String, *)
method overrides that support most primitive types (String, Boolean, Integer, Long, Double) as well as other types. We'll get to those later. For now, let's start with the basics:
JSONObject object = NodeFactory.newJSONObject(); //Shortcut for the Factory process
object.put("firstName", "Jim");
object.put("lastName", "Earley");
object.put("email", "[email protected]");
object.put("timestamp", 1613620307955); //long value representing a DateTime - we'll talk about ValueConverters later
object.put("loveJava", true);
object.put("pi", 3.1415926);
Using the prettyPrint()
method (inherited from JSONNode
) we'll see:
{
"firstName": "Jim",
"lastName": "Earley",
"email": "[email protected]",
"timestamp": 1613620307955,
"loveJava": true,
"pi": 3.1415926
}
Getting Values
There are several built-in get*
methods that will return a typed value. There is a get(String)
method which returns a JSONValue<T>
instance, but we'll get into that later. Using the example above:
String lastName = object.getString("lastName");
Double pi = object.getDouble("pi")
Long timestamp = object.getLong("timestamp");
boolean loveJava = object.getBoolean("loveJava");