I've been working on a task where I need to make a request and get value of a specific key in JSON. Because of some limitations/complications, I'm suppose to use only in-built libraries of Java.
For making a request, I'm using HttpURLConnection
but for parsing JSON I could not find. Could you please point me to Java in built JSON parsers.
I found similar question here but that does not have satisfactory answer and pretty old hence asking again, in case, this is available with latest versions of Java.
You can use built-in Nashorn engine in Java 8
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
});
}
}
source : Converting JSON To Map With Java 8 Without Dependencies
Disclaimer: Nashorn will be deprecated soon.
Update : Nashorn has been removed from Java 15
The Java API for JSON Processing provides portable APIs to parse, generate, transform, and query JSON.
Official Website Reference - https://www.oracle.com/technical-resources/articles/java/json.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With