Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
524 views
in Technique[技术] by (71.8m points)

java - Convert InputStream into JSON

I am using json-rpc-1.0.jar.Below is my code. I need to convert InputStream object into JSON since the response is in JSON.

I did verify the json response obtained from Zappos API. It is valid.

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);

I get the below mentioned exception:

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)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...