Simplest way to read json from a URL in java

后端 未结 11 1092
情书的邮戳
情书的邮戳 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:11

    It's very easy, using jersey-client, just include this maven dependency:

    
      org.glassfish.jersey.core
      jersey-client
      2.25.1
    
    

    Then invoke it using this example:

    String json = ClientBuilder.newClient().target("http://api.coindesk.com/v1/bpi/currentprice.json").request().accept(MediaType.APPLICATION_JSON).get(String.class);
    

    Then use Google's Gson to parse the JSON:

    Gson gson = new Gson();
    Type gm = new TypeToken() {}.getType();
    CoinDeskMessage cdm = gson.fromJson(json, gm);
    

提交回复
热议问题