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 {
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.
BoostHungry Jul 07 '15 at 17:10 2015-07-07 17:10
source share