[Java] Get Json from URL and handle it with standard API (javax.script)

Introduction

A memo that I investigated a little because I thought that I could not easily handle JSON without using a library in Java

I have confirmed and verified it with Java8, but it seems that javax.script is from Java6.

sample

Get the weather information with Get.

Weather Web Service Specifications --Weather Hacks --livedoor Weather Information http://weather.livedoor.com/weather_hacks/webservice

Sample class


public static void main(String[] args) {
  try {
    System.out.println("Tokyo weather");
    URL url = new URL("http://weather.livedoor.com/forecast/webservice/json/v1?city=130010");
    String json;
    //Get communication to String (enclosed in parentheses to eval)
    try (BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream()));) {
      json = br.lines().collect(Collectors.joining("", "(", ")"));
    }// ↑ "({"forecasts":[{"dateLabel":"x",...},{"dateLabel":"y",...},...],...})"Such a String

    Bindings jsObj = (Bindings) new ScriptEngineManager().getEngineByName("js").eval(json);

    jsObj = (Bindings) jsObj.get("forecasts");
    // get(key)You can get it with, but the return is Object type. Cast as needed

    //js array is values()so
    jsObj.values().stream()
        .map(o -> (Bindings) o)
        .map(o -> o.get("dateLabel") + "\t" + o.get("telop"))
        .forEach(System.out::println);

  } catch (Exception e) {
    e.printStackTrace();
  }//Exception handling is completely messy. sorry.
}

point

The important part is the cast to the interface javax.script.Bindings.

Instance when the return value of ScriptEngine.eval () is Object class and Json is executed by ScriptEngine [ScriptObjectMirror](https://docs.oracle.com/javase/jp/9/docs/api/jdk/nashorn /api/scripting/ScriptObjectMirror.html) etc. cannot be imported due to access restrictions and cannot be cast, so there is a lot of information on patterns that are operated by making full use of reflection.

The Bindings interface implemented by ScriptObjectMirror inherits from Map \ <String, Object >. So you can simply use Map methods such as get (String key), keySet (), values () without thinking too hard. No, if you don't know what the Bindings interface is, you can cast it to Map \ <?,? >.

Since the key is a String, I don't think there is any particular problem, but the return of get () etc. is also an Object class, so if Json is deeply nested, cast it with Bindings or Map and operate it. By the way, it seems that the javascript array is stored so that it can be accessed by the keys ("0", "1", "2", ...) whose index number is a character string. However, I think that it should be accessed using Map.values () in the first place.

Recommended Posts

[Java] Get Json from URL and handle it with standard API (javax.script)
Handle Java 8 date and time API with Thymeleaf with Spring Boot
Handle exceptions coolly with Java 8 lambda expressions and Stream API
[Kotlin] Get Java Constructor / Method from KFunction and call it
Access Web API on Android with Get and process Json (Java for the time being)
API integration from Java with Jersey Client
JSON in Java and Jackson Part ③ Embed JSON in HTML and use it from JavaScript
Get Value from URL parameter with GetMapping ~ LocalDate ~
[Java] How to get and output standard input
[Java] Get and display the date 10 days later using the Time API added from Java 8.
JSON with Java and Jackson Part 2 XSS measures
[Java] Get images with Google Custom Search API
[Android development] Get an image from the server in Java and set it in ImageView! !!
[Java] Get metadata from files with Apathce Tika, and get image / video width and height from metadata [Kotlin]
Handle JSON with minimal-json
Memorandum No.4 "Get a character string and decorate it" [Java]
JSON in Java and Jackson Part 1 Return JSON from the server
[Java] Get Charset with Apathce Tika / Initialize String from Charset [Kotlin]
Implement Java Interface in JRuby class and call it from Java
Get video information from Nikorepo and throw it to Slack
Correct the character code in Java and read from the URL
Get attributes and values from an XML file in Java
Convert Excel to Blob with java, save it, read it from DB and output it as a file!
[Java] JSON communication with jackson
Search and execute method by name from instance with processing (java)
Install the memcached plugin on MySQL and access it from Java
Java, JS (jQuery) and Ajax. Get a specific value of JSON.
Get Flux result of Spring Web Flux from JS with Fetch API
[Java] How to convert from String to Path type and get the path
Read barometric pressure and temperature with Java from Raspberry Pi 3 & BMP180
[Java] Output the result of ffprobe -show_streams in JSON and map it to an object with Jackson