5

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.

Alpha
  • 12,340
  • 22
  • 77
  • 141

3 Answers3

4

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

Smile
  • 3,484
  • 2
  • 25
  • 35
2

The Java API for JSON Processing provides portable APIs to parse, generate, transform, and query JSON.

enter image description here

Official Website Reference - https://www.oracle.com/technical-resources/articles/java/json.html

Suryakant Bharti
  • 632
  • 1
  • 5
  • 23
  • OP wants to use built-in libraries. This is an API and you would need to use a 3rd implementation library. – Smile Jan 20 '20 at 10:19
0

There is no such libraries in Java. But if you use maven, you can add GSON or JSON-lib dependencies.

devNNP
  • 59
  • 4