JSON with Jackson
A package of Maven Central used from Ring: read a tree, find a path, write and pretty print.
What you will learn#
jMavenClassesto download a package and make its Ring classes,ObjectMapper,readTreeand a JSON path,- writing JSON from a Map or a list,
- pretty printing.
The program#
# Tutorial 13: JSON with Jackson - a package of Maven Central used from Ring
load "java.ring"
# jMavenClasses downloads the jar and everything it needs, and makes the Ring classes of the packages that you name
jMavenClasses("com.fasterxml.jackson.core:jackson-databind:2.17.0",["com.fasterxml.jackson.databind","com.fasterxml.jackson.databind.node"])
using {
"com.fasterxml.jackson.databind"
"com.fasterxml.jackson.databind.node"
"java.util"
}
oMapper = new ObjectMapper
# 1. reading: readTree gives a tree of nodes
cJson = '{ "name": "RingJava", "tags": ["ring", "java"], "version": { "major": 1, "minor": 0 }, "stable": true }'
oTree = oMapper.readTree(cJson)
? oTree.@get("name").asText(NULL)
? oTree.@get("version").@get("minor").asInt(NULL)
? oTree.@get("stable").asBoolean(NULL)
? oTree.has("missing")
aTags = oTree.@get("tags").toList()
for oTag in aTags
? "tag: " + oTag.asText(NULL)
next
# 2. a path: find a value deep in the tree
? oTree.at("/version/major").asInt(NULL)
# 3. writing: a Java Map or List becomes JSON text
oMap = new LinkedHashMap
oMap.@put("language","Ring")
oMap.@put("year",2016)
oMap.@put("tags",new ArrayList(["simple","fast"]))
? oMapper.writeValueAsString(oMap)
# 4. pretty printing
? oMapper.writerWithDefaultPrettyPrinter().writeValueAsString(oMap)
# 5. a Ring list of lists becomes JSON by hand, with the tree classes
oArray = oMapper.createArrayNode()
for nI = 1 to 3
oItem = oMapper.createObjectNode()
oItem.@put("id",nI)
oItem.@put("square",nI * nI)
oArray.add(oItem)
next
? oArray.toString()
# 6. a Map from JSON
oBack = oMapper.readValue([cJson,"java.util.Map"]) # a class is passed as its name
? oBack.@get("name")RingJava
0
1
0
tag: ring
tag: java
1
{"language":"Ring","year":2016,"tags":["simple","fast"]}
{
"language" : "Ring",
"year" : 2016,
"tags" : [ "simple", "fast" ]
}
[{"id":1,"square":1},{"id":2,"square":4},{"id":3,"square":9}]
RingJavaHow it works#
jMavenClasses downloads the package with what it needs and generates the Ring classes of the packages you name, so ObjectMapper works like a class of the JDK. Nodes of the tree have get, path and asText; at("/a/b") finds a value deep in the tree.
Exercises#
- Read a JSON text with a list and sum its numbers.
- Convert a Ring list of lists to JSON.
- Print only the keys of an object.