{"@attributes":{"version":"2.0"},"channel":{"title":"Radomir Sohlich","link":"https:\/\/sohlich.github.io\/tags\/jackson\/index.xml","description":"Recent content on Radomir Sohlich","generator":"Hugo -- gohugo.io","copyright":"\u00a9 2017 Radomir Sohlich","item":{"title":"Streaming JSON with Jackson","link":"https:\/\/sohlich.github.io\/post\/jackson\/","pubDate":"Wed, 08 Feb 2017 20:27:44 +0100","guid":"https:\/\/sohlich.github.io\/post\/jackson\/","description":"<p>Sometimes there is a situation, when it is more\nefficient to parse the JSON in stream way.\nEspecially if you are dealing with huge input\nor slow connection. In that case the JSON need to be read\nas it comes from input part by part.\nThe side effect of such approach is that you are able to\nread corrupted JSON arrays in some kind of comfortable way.<\/p>\n\n<p>Well known Jackson library (<a href=\"https:\/\/github.com\/FasterXML\/jackson-core\">https:\/\/github.com\/FasterXML\/jackson-core<\/a>)\nprovides so called stream API to handle it.\nThe parsing of stream is possible via\nJsonParser object, which uses token approach.<\/p>\n\n<pre><code>InputStream is = new FileInputStream(&quot;data.json&quot;);\nJsonFactory factory = new JsonFactory();\nJsonParser parser = factory.createJsonParser(is);\n<\/code><\/pre>\n\n<p>To simplify the approach, the combination of ObjectMapper\nwith sequetial reading of JSON data could be used.The code of the\ncomplete solution could be like:<\/p>\n\n<pre><code>public void tryParse(InputStream is) throws IOException {\n\t\tJsonFactory factory = new JsonFactory();\n\t\tJsonParser parser = factory.createJsonParser(is);\n\t\tObjectMapper mapper = new ObjectMapper()\n\t\t\t\t.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES,false);\n\n\t\tJsonToken token = parser.nextToken();\n\t\t\n        \t\/\/ Try find at least one object or array.\n\t\twhile (!JsonToken.START_ARRAY.equals(token) &amp;&amp; token != null &amp;&amp; !JsonToken.START_OBJECT.equals(token)) {\n\t\t\tparser.nextToken();\n\t\t}\n\n\t\t\/\/ No content found\n\t\tif (token == null) {\n\t\t\treturn;\n\t\t}\n\n\t\tboolean scanMore = false;\n\n\t\twhile (true) {\n\t\t\t\/\/ If the first token is the start of obejct -&gt;\n\t\t\t\/\/ the response contains only one object (no array)\n\t\t\t\/\/ do not try to get the first object from array.\n\t\t\ttry {\n\t\t\t\tif (!JsonToken.START_OBJECT.equals(token) || scanMore) {\n\t\t\t\t\ttoken = parser.nextToken();\n\t\t\t\t}\n\t\t\t\tif (!JsonToken.START_OBJECT.equals(token)) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tif (token == null) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tObject node = mapper.readValue(parser, mappedClass);\n\t\t\t\t\n\t\t\t\t\/\/YOUR CODE TO HANDLE OBJECT\n\t\t\t\t\/\/...\n\n\n\t\t\t\tscanMore = true;\n\t\t\t} catch (JsonParseException e) {\n\t\t\t\thandleParseException(e);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n<\/code><\/pre>\n"}}}