Home  >  Jackson API

Jackson JsonNode.forEach() with Java 8 Consumer

By Arvind Rai, March 02, 2015
Jackson has provided JsonNode.forEach() method which will accept Java 8 consumer definition to iterate each node. The consumer accepts only super classes of JsonNode. It has been defined as below.
forEach(Consumer<? super JsonNode>  arg) 
We can define consumer only with super class of JsonNode. Now find the simple example to parse JSON and iterating it using Java 8 consumer. First find the input file.
info.json
{
  "id":1,
  "name":"Arvind",
  "village":"Dhananjaypur",
  "district":"Varanasi",
  "state":"UP"
}  
Now find the code which is parsing the JSON
IterateJSONwithConsumer.java
package com.concretepage;
import java.io.File;
import java.io.IOException;
import java.util.function.Consumer;
import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.map.ObjectMapper;
public class IterateJSONwithConsumer {
	public static void main(String[] args) throws JsonParseException, IOException {
		JsonFactory jsonFactory = new JsonFactory();
		JsonParser jp = jsonFactory.createJsonParser(new File("D:/cp/info.json"));
		jp.setCodec(new ObjectMapper());
		JsonNode jsonNode = jp.readValueAsTree();
                Consumer<JsonNode> data = (JsonNode node) -> System.out.println(node.asText());
                jsonNode.forEach(data);
	}
} 
Find the output.
1
Arvind
Dhananjaypur
Varanasi
UP 
POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS


©2018 concretepage.com | Privacy Policy | Contact Us