HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Java JSON Stringifier with the Nashorn API

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
thenashornwithjavastringifierjsonapi

Problem

I have written a Java JSON stringifier with the Nashorn API. Since this code is slow, I wanted to ask if I can improve it. My target is the highest possible performance to make it an alternative to other JSON libraries.

JSON.java

package com.example.json;

import java.util.Map;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

import com.example.json.util.TextFile;

public class JSON {

    private static final Invocable inv = create();

    private static final Invocable create() {
        ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
        try {
            engine.eval(TextFile.readFromResource("/js/json-stringify.js"));
        } catch (ScriptException e) {
            e.printStackTrace();
        }
        return (Invocable) engine;
    }

    public static final String stringify(Map json) {
        try {
            return (String) inv.invokeFunction("stringifyJSON", json);
        } catch (ScriptException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
        return null;
    }

}


JSONObject.java

package com.example.json.stringify;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

public class JSONObject {

    private Map map = new HashMap();

    public void appendChild(String key, Object object) {
        map.put(key, object);
    }

    public static final Map convertToJavaScript(JSONObject obj) {
        return obj.map;
    }

}


JSONArray.java

```
package com.example.json.stringify;

public class JSONArray {

private Object[] array;

public JSONArray(int length) {
array = new Object[length];
}

public void set(int index, Object object) {
if (index >= 0 && index <= array.length - 1) array[index] = object;
}

public static final Object[] convertToJavaScript(JSONArra

Solution

you can get JSON from engine by

ScriptObjectMirror json = (ScriptObjectMirror) engine.eval("JSON");


and call it's parse or stringify method via:

json.callMember("stringify", object);
json.callMember("parse", str)

Code Snippets

ScriptObjectMirror json = (ScriptObjectMirror) engine.eval("JSON");
json.callMember("stringify", object);
json.callMember("parse", str)

Context

StackExchange Code Review Q#91184, answer score: 8

Revisions (0)

No revisions yet.