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.
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.
}
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