{% extends "base.html" %} {% block title %}Siena JSON support{% endblock %} {% block body %}
Siena comes with a JSON implementation. This implementation is contained in a sigle class:
siena.Json
. A Json
object wraps any kind of JSON structure. This is, a Json
object can contain a boolean value, a String, a Map, a List, a number or null
. You can
know wich type of object is wrapped using its isXXX()
methods:
isString()
, isNumber()
, isBoolean()
, isMap()
,
isList()
or isNull()
.
If you like the siena's JSON implementation you can use it individually. If you want to persist complex
data structures into a database using siena you can use Json
objects directly in your
persistent classes. Siena will care about serializating and deserializating the object into Strings.
To start using siena.Json
the best is to import the class and all its members:
import siena.Json; import static siena.Json.*;
Create a map:
Json json = map().put("key1", 1234) .put("key2", true) .put("key3", null) .put("key4", "foo"); System.out.println(json);
The output:
{"key1": 1234, "key2": true, "key3": null, "key4": "foo"}
Retrieving data from previous map:
int value1 = json.get("key1").asInt();
You have several asXXX() methods.
Create a list:
Json json = list("foo", "bar", "baz", true, false, null, 1234);
The output:
["foo", "bar", "baz", true, false, null, 1234]
Retrieving data from previous list:
int size = json.size(); boolean b = json.at(3).bool();
Complex example:
Json json = list("foo", "bar", "baz", map().put("key1", true) .put("key2", false) .put("key3", list(1, 2, 3, 4))); System.out.println(json);
The output:
["foo", "bar", "baz", {"key1": true, "key2": false, "key3": [1, 2, 3, 4]}]
Json json = loads("[true, false, null, {}]"); System.out.println(json);
The output:
[true, false, null, {}]
The buit-in siena JSON implementaiton lets you create Json
objects from
plain Java arrays or collections. The Json
constructor accepts
arrays, collections and maps. Examples:
Json fromArray = new Json(new Object[]{1, 2, 3});
Json fromCollection = new Json(Arrays.asList(new Object[]{1, 2, 3}));
Map<String, Object> m = new HashMap<String, Object>(); m.put("foo", 1); Json fromMap = new Json(m);{% endblock %}