is it possible to proccess JSON responses with the JDK or HttpComponents only?

后端 未结 3 1555
抹茶落季
抹茶落季 2020-12-02 01:30

we are upgrading our web app to use Facebook\'s Graph API, which returns JSON responses. However we don\'t want to add dependecy to a JSON library unless we have no other ch

3条回答
  •  孤城傲影
    2020-12-02 01:33

    Unfortunately, native JSON support was delayed past Java 9.

    But for the sake of sportmanship here is plain Java 8 hacky solution using Nashorn JavaScript engine without any external dependency:

    String json = "{\"foo\":1, \"bar\":\"baz\"}";
    ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
    Object o = engine.eval(String.format("JSON.parse('%s')", json));
    Map map = (Map) o;
    System.out.println(Arrays.toString(map.entrySet().toArray()));
    // [foo=1, bar=baz]
    

    Since Java 8u60 JSON.parse can be substituted with Java.asJSONCompatible which does better handling of JSON arrays.

    Credits:

    Effective way to pass JSON between java and javascript

    https://dzone.com/articles/mapping-complex-json-structures-with-jdk8-nashorn

提交回复
热议问题