Categories
Java Java-Json binding by Jackson Uncategorized

JSON Streaming

Jackson Streaming provides set of Streaming APIs to read from or Write to JSON as string. It is streaming oriented hence takes less memory footprint, it is analogous to Stax Streaming API for XML operations.

We will see simple example to write JSON string into .json file. Then read .json for input JSON string to be converted to Java Map object.

App.java

package custom.jackson.learning;

import java.io.File;
import java.io.IOException;
import java.util.Map;

import com.fasterxml.jackson.core.JsonEncoding;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.ObjectMapper;

public class App {

	public static void main(String[] args) throws IOException {
		
		//Write to JSON string to .json file
		 JsonFactory jsonFactory = new JsonFactory();
		 JsonGenerator jsonGenerator = jsonFactory.createGenerator(new File("Employee.json"), JsonEncoding.UTF8);

		 //start writing the JSON object
		 jsonGenerator.writeStartObject();
		 
		 //"firstName":"Suresh"
		 jsonGenerator.writeStringField("firstName", "Suresh");
		 
		 //"lastName":"Rana"
		 jsonGenerator.writeStringField("lastName", "Rana");
		 
		 //"skills":["Java","PHP","SQL"]
		 jsonGenerator.writeFieldName("skills");
		 jsonGenerator.writeStartArray();
		 jsonGenerator.writeString("Java");
		 jsonGenerator.writeString("PHP");
		 jsonGenerator.writeString("SQL");
		 jsonGenerator.writeEndArray();
		 
		 //"certified":true
		 jsonGenerator.writeBooleanField("certified", true);
		 
		 //"age":21
		 jsonGenerator.writeNumberField("age", 21);
		 
		//end writing the JSON object
		 jsonGenerator.writeEndObject();
		 jsonGenerator.close();
		
		 System.out.println("JSON Writing to Employee.json completed.");
		 
		 //read the JSON file as input and convert to Map object
		 System.out.println("Reading data from Employee.json file");
		 ObjectMapper mapper = new ObjectMapper();
         Map employeeMap = mapper.readValue(new File("Employee.json"), Map.class);
         
         System.out.println("Map created from Employee.json file ::"+employeeMap);
         
	}

}


output ::

Generated Employee.json

Leave a comment

Design a site like this with WordPress.com
Get started