RingJavafor Ring

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#

The program#

samples/UsingJava/tutorials/ch13_json.ring
# 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")
Output
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}]
RingJava

How 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#

  1. Read a JSON text with a list and sum its numbers.
  2. Convert a Ring list of lists to JSON.
  3. Print only the keys of an object.

Next#

HTML with jsoup

RingJava - use Java classes and methods from Ring programs.