Parsing JSON in XPages Applications
Thu May 21 12:47:53 EDT 2015
David Leedy pointed out to me that a post I made last year about generating JSON in XPages left out a crucial bit of followup: reading that JSON back in. This topic is a bit simpler to start with, since there's really just one entrypoint: com.ibm.commons.util.io.json.JsonParser.fromJson(...)
.
There are a few variants of this method to provide either a callback to call during parsing or a List
to fill with the result, but most of the time you're going to use the variants that take a String
or Reader
of JSON and convert it into a set of Java objects. As with generating JSON, the first parameter here is a JsonJavaFactory
, and which static instance
property you choose matters a bit. Contrary to the first-Google-result documentation, there are three types, and they differ slightly in the types of objects they output:
instance
: This usesjava.util.HashMap
for JSON objects/maps andjava.util.ArrayList
for JSON arrays.instanceEx
: This is likeinstance
, but usesJsonJavaObject
for JSON objects/maps.instanceEx2
: LikeinstanceEx
, this usesJsonJavaObject
for objects/maps but also usesJsonArray
for JSON arrays.
Since JsonJavaObject
and JsonArray
implement the normal Map<String, Object>
and List<Object>
interfaces you'd expect (and, indeed, subclass HashMap
and ArrayList
), you can treat them interchangeably if you're just using the interfaces like you should, but it may matter if you're doing something where you expect certain traits of one of the concrete classes or want to use the explicit getString
, etc. methods on the JSON-specific ones.*
Anyway, with that out of the way, the actual code to use these is pretty straightforward:
String json = "{ \"foo\": 1, \"bar\": 2}"; Map<String, Object>result = (Map<String, Object>)JsonParser.fromJson(JsonJavaFactory.instance, json);
In this case, I'm immediately casting the result from Object
to Map
because I'm sure of the contents of the JSON. If you're less confident, you should surround it with instanceof
tests before doing something like that. In any event, that's pretty much all there is to it. As with generating JSON, SSJS wraps this functionality in a fromJson
method (which may or may not produce the same objects; I haven't checked).
* You could also subclass the standard as the code does if you have specific needs or desires, like using a LinkedHashMap
instead of HashMap
to preserve the order of the object's keys.