Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@donnfelker
Last active August 26, 2019 15:41
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save donnfelker/5391295 to your computer and use it in GitHub Desktop.
Save donnfelker/5391295 to your computer and use it in GitHub Desktop.
// Connect to your API with your http lib, i use http-request: https://github.com/kevinsawicki/http-request
// Then get the reader. The 'request' variable below is just a HttpRequest object
// as shown here: http://kevinsawicki.github.io/http-request/
final Reader reader = request.reader();
final ObjectMapper mapper = new ObjectMapper();
final JsonFactory factory = mapper.getFactory();
// Create a new streaming parser with the reader
JsonParser jp = factory.createParser(reader);
// I'm working with a JSON Array that is returned from the API that I'm connecting to, so I need to advance the
// parser to the start of the array.
// Advance stream to START_ARRAY first:
jp.nextToken();
// Parse each value by looking for each start object. The Mapper will read the object and advance the parser
// until it finds the END_OBJECT at which time the mapper then deserializes into a POJO. Then the loop will
// continue to the next position. This will handle each JSON object as it becomes available and will be very
// light on memory and high in performance.
while(jp.nextToken() == JsonToken.START_OBJECT) {
// Get customer POJO
final Customer c = mapper.readValue(jp, Customer.class);
// Update local db with customer info.
myDataLayer.updateCustomer(c);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment