Skip to content

Instantly share code, notes, and snippets.

@h3xxx
Created October 21, 2015 19:19
Show Gist options
  • Save h3xxx/359e9f1a40f1c58e1b8b to your computer and use it in GitHub Desktop.
Save h3xxx/359e9f1a40f1c58e1b8b to your computer and use it in GitHub Desktop.
Converting JSON To Map With Java 8 Without Dependencies. Starting with JDK 8u60+ the built-in Nashorn engine is capable to convert Json content into java.util.Map. No external dependencies are required for parsing, Origin: http://adam-bien.com/roller/abien/entry/converting_json_to_map_with
// Converting JSON To Map With Java 8 Without Dependencies.
// Starting with JDK 8u60+ the built-in Nashorn engine is capable to convert Json content into java.util.Map.
// No external dependencies are required for parsing,
// Origin: http://adam-bien.com/roller/abien/entry/converting_json_to_map_with
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Map;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
public class JSONParsingTest {
private ScriptEngine engine;
@Before
public void initEngine() {
ScriptEngineManager sem = new ScriptEngineManager();
this.engine = sem.getEngineByName("javascript");
}
@Test
public void parseJson() throws IOException, ScriptException {
String json = new String(Files.readAllBytes(/*path*/);
String script = "Java.asJSONCompatible(" + json + ")";
Object result = this.engine.eval(script);
assertThat(result, instanceOf(Map.class));
Map contents = (Map) result;
contents.forEach((t, u) -> {
//key-value pairs
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment