Simplest way to read json from a URL in java

后端 未结 11 930
情书的邮戳
情书的邮戳 2020-11-22 04:15

This might be a dumb question but what is the simplest way to read and parse JSON from URL in Java?

In Groovy, it\

11条回答
  •  有刺的猬
    2020-11-22 05:15

    Here are couple of alternatives versions with Jackson (since there are more than one ways you might want data as):

      ObjectMapper mapper = new ObjectMapper(); // just need one
      // Got a Java class that data maps to nicely? If so:
      FacebookGraph graph = mapper.readValue(url, FaceBookGraph.class);
      // Or: if no class (and don't need one), just map to Map.class:
      Map map = mapper.readValue(url, Map.class);
    

    And specifically the usual (IMO) case where you want to deal with Java objects, can be made one liner:

    FacebookGraph graph = new ObjectMapper().readValue(url, FaceBookGraph.class);
    

    Other libs like Gson also support one-line methods; why many examples show much longer sections is odd. And even worse is that many examples use obsolete org.json library; it may have been the first thing around, but there are half a dozen better alternatives so there is very little reason to use it.

提交回复
热议问题