将InputStream转换为JSON
我正在使用json-rpc-1.0.jar。以下是我的代码。由于响应为JSON,因此我需要将InputStream对象转换为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);
我得到以下提到的异常:
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)
回答:
利用Jackson JSON解析器。
推荐- 杰克逊之家
您唯一需要做的是-
ObjectMapper mapper = new ObjectMapper();Map<String, Object> jsonMap = mapper.readValue(inputStream, Map.class);
现在jsonMap
将包含JSON。
以上是 将InputStream转换为JSON 的全部内容, 来源链接: utcz.com/qa/435636.html