2020-02-19

Java 11 - Passing JSON Objects to Java

The function Java.asJSONCompatible(obj) accepts a script object and returns an
object that is compatible with the expectations of most Java JSON libraries: it exposes
all arrays as List objects (rather than Map objects) and all other objects as Map objects.


Mapping Data Types mentions that every JavaScript object, when exposed to Java
APIs, implements the java.util.Map interface. This is true even for JavaScript arrays.
However, this behavior is often not desired or expected when Java code expects
JSON-parsed objects. Java libraries that manipulate JSON-parsed objects usually
expect arrays to expose the java.util.List interface instead. If you need to expose
your JavaScript objects in such a manner that arrays are exposed as lists and not
maps, use the Java.asJSONCompatible(obj) function, where obj is the root of your
JSON object tree.

Example:

import javax.script.*;
import java.util.*;
public class JSONTest {
 public static void main(String[] args) throws Exception {
 ScriptEngineManager m = new ScriptEngineManager();
 ScriptEngine e = m.getEngineByName("nashorn");
 Object obj1 = e.eval(
 "JSON.parse('{ \"x\": 343, \"y\": \"hello\", \"z\": [2,4,5] }');");
 Map<String, Object> map1 = (Map<String, Object>)obj1;
 System.out.println(map1.get("x"));
 System.out.println(map1.get("y"));
 System.out.println(map1.get("z"));
 Map<Object, Object> array1 = (Map<Object, Object>)map1.get("z");
 array1.forEach((a, b) -> System.out.println("z[" + a + "] = " + b));
 System.out.println();

 Object obj2 = e.eval(
 "Java.asJSONCompatible({ \"x\": 343, \"y\": \"hello\", \"z\":
[2,4,5] })");
 Map<String, Object> map2 = (Map<String, Object>)obj2;
 System.out.println(map2.get("x"));
 System.out.println(map2.get("y"));
 System.out.println(map2.get("z"));
 List<Object> array2 = (List<Object>)map2.get("z");
 array2.forEach(a -> System.out.println(a));
 }
}

This example prints the following:
343
hello
[object Array]
z[0] = 2
z[1] = 4
z[2] = 5
343
hello
[2, 4, 5]
2
4
5

No comments:

Post a Comment