Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java in-built JSON parser [closed]

Tags:

java

json

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.

like image 309
Alpha Avatar asked Jan 20 '20 09:01

Alpha


2 Answers

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

like image 152
Smile Avatar answered Nov 10 '22 17:11

Smile


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

like image 2
Suryakant Bharti Avatar answered Nov 10 '22 17:11

Suryakant Bharti