JsonMap and JsonList
The JsonMap and JsonList classes are generic Java representations of JSON objects and arrays. These classes can be used to create "unstructured" models for serialization (as opposed to "structured" models consisting of beans).
If you want to quickly generate JSON/XML/HTML from generic maps/collections, or parse JSON/XML/HTML into generic maps/collections, these classes work well.
These classes extend directly from the following JCF classes:
The JsonMap and JsonList classes are very similar to the JSONObject
and JSONArray
classes found in other libraries.
However, the names were chosen because the concepts of Maps
and Lists
are already familiar to Java programmers, and
these classes can be used with any of the serializers or parsers.
These object can be serialized in one of three ways:
- Using the provided JsonMap.writeTo(java.io.Writer) or JsonList.writeTo(java.io.Writer) methods.
- Passing them to one of the Serializer serialize methods.
- Simply calling the JsonMap.asJson()/JsonMap.toString() or JsonList.asString()/JsonList.toString() methods which will serialize it as JSON5.
Any valid JSON can be parsed into an unstructured model consisting of generic JsonMap and JsonList objects. (Any valid XML can also be parsed into an unstructured model)
// Parse an arbitrary JSON document into an unstructered data model
// consisting of JsonMaps, JsonLists, and java primitive objects.
String json = "{a:{name:'John Smith',age:21},b:{name:'Joe Smith',age:42}}";
JsonMap map = Json.to(json, JsonMap.class);
// Use JsonMap API to extract data from the unstructured model.
int johnSmithAge = map.getMap("a").getInt("age");
// Convert it back into JSON.
json = Json.of(map);
// Or convert it to XML.
String xml = Xml.of(map);
// Or just use toString() or asJson().
json = map.toString();
json = map.asJson();
The JsonMap and JsonList classes have many convenience features:
// Convert the map to a bean.
MyBean myBean = map.cast(MyBean.class);
// Find entries by multiple keys.
MyBean myBean = map.find(MyBean.class, "key1", "key2");
// Fluent-style appenders.
map.append("key1", "val1").append("key2", "val2");
// REST-like functions for manipulating nodes in the data structure using URL-like notation.
map.getAt("foo/bar/myBean", MyBean.class);
map.putAt("foo/bar/myBean", MyBean.class);
map.postAt("foo/bar/myListOfBeans", MyBean.class);
map.deleteAt("foo/bar/myBean");
// Copy with inclusion or exclusion.
JsonMap map2 = map.include("key1", "key2", "key3");
JsonMap map3 = map.exclude("key1", "key2", "key3");
// Serialize using another serializer.
String xml = map.serializeTo(XmlSerializer.DEFAULT);
// Nested maps.
map.inner(anotherMap);