How to parse JSON input stream

I use java to call a URL that returns a JSON object:

url = new URL("my URl"); urlInputStream = url.openConnection().getInputStream(); 

How can I convert the answer to a lowercase form and parse it?

+45
java json android
Jun 28 '11 at 19:13
source share
7 answers

I would advise you to use Reader to convert your InputStream.

 BufferedReader streamReader = new BufferedReader(new InputStreamReader(in, "UTF-8")); StringBuilder responseStrBuilder = new StringBuilder(); String inputStr; while ((inputStr = streamReader.readLine()) != null) responseStrBuilder.append(inputStr); new JSONObject(responseStrBuilder.toString()); 

I tried in.toString (), but it returns:

 getClass().getName() + '@' + Integer.toHexString(hashCode()) 

(e.g. documentation says that it is being output to toString from Object)

+74
Nov 07 '12 at 10:25
source share

All current answers suggest that everything is in order to pull all the JSON into memory, where the advantage of InputStream is that you can read the input gradually. If you want to not read the entire Json file at once, I would suggest using the Jackson library (this is my personal favorite, but I'm sure others like Gson have similar features).

With Jackson, you can use JsonParser to read one section at a time. Below is an example of the code I wrote that wraps the reading of a JsonObjects array in Iterator. If you just want to see the Jackson example, look at the initJsonParser, initFirstElement, and initNextObject methods.

 public class JsonObjectIterator implements Iterator<Map<String, Object>>, Closeable { private static final Logger LOG = LoggerFactory.getLogger(JsonObjectIterator.class); private final InputStream inputStream; private JsonParser jsonParser; private boolean isInitialized; private Map<String, Object> nextObject; public JsonObjectIterator(final InputStream inputStream) { this.inputStream = inputStream; this.isInitialized = false; this.nextObject = null; } private void init() { this.initJsonParser(); this.initFirstElement(); this.isInitialized = true; } private void initJsonParser() { final ObjectMapper objectMapper = new ObjectMapper(); final JsonFactory jsonFactory = objectMapper.getFactory(); try { this.jsonParser = jsonFactory.createParser(inputStream); } catch (final IOException e) { LOG.error("There was a problem setting up the JsonParser: " + e.getMessage(), e); throw new RuntimeException("There was a problem setting up the JsonParser: " + e.getMessage(), e); } } private void initFirstElement() { try { // Check that the first element is the start of an array final JsonToken arrayStartToken = this.jsonParser.nextToken(); if (arrayStartToken != JsonToken.START_ARRAY) { throw new IllegalStateException("The first element of the Json structure was expected to be a start array token, but it was: " + arrayStartToken); } // Initialize the first object this.initNextObject(); } catch (final Exception e) { LOG.error("There was a problem initializing the first element of the Json Structure: " + e.getMessage(), e); throw new RuntimeException("There was a problem initializing the first element of the Json Structure: " + e.getMessage(), e); } } private void initNextObject() { try { final JsonToken nextToken = this.jsonParser.nextToken(); // Check for the end of the array which will mean we're done if (nextToken == JsonToken.END_ARRAY) { this.nextObject = null; return; } // Make sure the next token is the start of an object if (nextToken != JsonToken.START_OBJECT) { throw new IllegalStateException("The next token of Json structure was expected to be a start object token, but it was: " + nextToken); } // Get the next product and make sure it not null this.nextObject = this.jsonParser.readValueAs(new TypeReference<Map<String, Object>>() { }); if (this.nextObject == null) { throw new IllegalStateException("The next parsed object of the Json structure was null"); } } catch (final Exception e) { LOG.error("There was a problem initializing the next Object: " + e.getMessage(), e); throw new RuntimeException("There was a problem initializing the next Object: " + e.getMessage(), e); } } @Override public boolean hasNext() { if (!this.isInitialized) { this.init(); } return this.nextObject != null; } @Override public Map<String, Object> next() { // This method will return the current object and initialize the next object so hasNext will always have knowledge of the current state // Makes sure we're initialized first if (!this.isInitialized) { this.init(); } // Store the current next object for return final Map<String, Object> currentNextObject = this.nextObject; // Initialize the next object this.initNextObject(); return currentNextObject; } @Override public void close() throws IOException { IOUtils.closeQuietly(this.jsonParser); IOUtils.closeQuietly(this.inputStream); } } 

If you don't care about memory usage, then of course it would be easier to read the whole file and parse it as one big Json, as mentioned in other answers.

+21
Jul 07 '15 at 17:10
source share

use jackson to convert json input stream to map or object http://jackson.codehaus.org/

there are also other useful libraries for json, you can google: json java

+6
Jun 28. '11 at 19:15
source share

For those who have pointed out that you cannot use the toString InputStream method like this, see https://stackoverflow.com/a/168268/2126 :

My correct answer would be the following:

 import org.json.JSONObject; public static String convertStreamToString(java.io.InputStream is) { java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A"); return s.hasNext() ? s.next() : ""; } ... JSONObject json = new JSONObject(convertStreamToString(url.openStream()); 
+5
Jan 29 '13 at 15:02
source share

Use the library.

  • GSON
  • Jackson
  • or one of the many other JSON libraries that are there.
+4
Jun 28 '11 at 19:17
source share

If you want to use the Jackson Databind (which Spring uses by default for its HttpMessageConverters ), you can use the ObjectMapper.readTree (InputStream) API . For example,

 ObjectMapper mapper = new ObjectMapper(); JsonNode json = mapper.readTree(myInputStream); 
+1
Jun 07 '17 at 13:53 on
source share
 { InputStream is = HTTPClient.get(url); InputStreamReader reader = new InputStreamReader(is); JSONTokener tokenizer = new JSONTokener(reader); JSONObject jsonObject = new JSONObject(tokenizer); } 
-3
Mar 23 2018-12-23T00:
source share



All Articles