Convert InputStream into JSON

只愿长相守 提交于 2019-11-29 05:52:06

Make use of Jackson JSON parser.

Refer - Jackson Home

The only thing you need to do -

ObjectMapper mapper = new ObjectMapper();
Map<String, Object> jsonMap = mapper.readValue(inputStream, Map.class);

Now jsonMap will contain the JSON.

ObjectMapper.readTree(InputStream) easily let's you get nested JSON with JsonNodes.

public void testMakeCall() throws IOException {
    URL url = new URL("https://api.coindesk.com/v1/bpi/historical/close.json?start=2010-07-17&end=2018-07-03");
    HttpURLConnection httpcon = (HttpURLConnection) url.openConnection();
    httpcon.addRequestProperty("User-Agent", "Mozilla/4.0");
    InputStream is = httpcon.getInputStream();

    try {
        ObjectMapper mapper = new ObjectMapper();
        JsonNode jsonMap = mapper.readTree(is);
        JsonNode bpi = jsonMap.get("bpi");
        JsonNode day1 = bpi.get("2010-07-18");

        System.out.println(bpi.toString());
        System.out.println(day1.toString());
    } finally {
        is.close();
    }
}

Result:

{"2010-07-18":0.0858,"2010-07-19":0.0808,...}

0.0858

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!