将InputStream转换为JSON

Mar*_*rgi 14 java json-rpc

我正在使用json-rpc-1.0.jar.Below是我的代码.我需要将InputStream对象转换为JSON,因为响应是在JSON中.

我确实验证了从Zappos API获得的json响应.这是有效的.

PrintWriter out = resp.getWriter();
String jsonString = null;
URL url = new URL("http://api.zappos.com/Search?term=boots&key=my_key");
InputStream inputStream = url.openConnection().getInputStream();
resp.setContentType("application/json");

JSONSerializer jsonSerializer = new JSONSerializer();
try {
   jsonString = jsonSerializer.toJSON(inputStream);
} catch (MarshallException e) {
 e.printStackTrace();
    }
out.print(jsonString);
Run Code Online (Sandbox Code Playgroud)

我得到以下提到的例外:

com.metaparadigm.jsonrpc.MarshallException: can't marshall sun.net.www.protocol.http.HttpURLConnection$HttpInputStream
    at com.metaparadigm.jsonrpc.JSONSerializer.marshall(JSONSerializer.java:251)
    at com.metaparadigm.jsonrpc.JSONSerializer.toJSON(JSONSerializer.java:259)
    at Communicator.doGet(Communicator.java:33)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:740)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:247)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:193)
    at filters.ExampleFilter.doFilter(ExampleFilter.java:149)
Run Code Online (Sandbox Code Playgroud)

Vis*_*ale 42

使用Jackson JSON解析器.

推荐 - 杰克逊之家

你唯一需要做的事 -

ObjectMapper mapper = new ObjectMapper();
Map<String, Object> jsonMap = mapper.readValue(inputStream, Map.class);
Run Code Online (Sandbox Code Playgroud)

现在jsonMap将包含JSON.


Phi*_*ego 6

ObjectMapper.readTree(InputStream) 可以轻松地让您使用 JsonNodes 获取嵌套的 JSON。

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

结果:

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

0.0858