JSON File Generator in JAVA

Java JSON API’s allows programmers to read, process and transform Java objects to JSON and back where JSON is Java Script Object Notation.

There are lot of Java JSON API’s available for instance:

  1. Jackson API
  2. FlexJSON
  3. GSON

FlexJSON Example: Flex JSON is a very lightweight library for serialising and deserialising the Java objects to and from JSON


import java.io.File;

import java.io.IOException;

import java.util.List;

import flexjson.JSONSerializer;

import org.apache.commons.io.FileUtils;

import org.apache.log4j.Logger;

import org.codehaus.jackson.map.ObjectMapper;


* @author lsuri <lakshay13@gmail.com>


public class JSONCreator {


private static final Logger LOGGER = Logger.getLogger(JSONCreator.class);

private static final ObjectMapper INSTANCE = new ObjectMapper();

private JSONCreator() {


public static JSONCreator newInstance() {

return new JSONCreator();


// method which is called by passing a list of Java Objects to be converted to JSON

public String createJsonTemplate(List<ApiPojo> list) {

File tempFile = null;

String packageContent = null;

try {

String fileNamePrefix = “package”;

// creates a temp file with JSON extension

tempFile = File.createTempFile(fileNamePrefix, “.json”);

LOGGER.info(“File location” + tempFile.getAbsolutePath());

// STEP 1: Create JSON Serializer.

JSONSerializer serializer = new JSONSerializer();

// STEP 2: Exclude the fields not to be serialised.

packageContent = serializer.exclude(“empSalary”, “empAddress”, “empMaritialStatus”).serialize(list);

// Step 3: Writing to a tempFile (JSON) the serialised value.

FileUtils.writeStringToFile(tempFile, packageContent);

} catch (IOException e) {

LOGGER.error(“Error converting the list of Java Objects to JSON”, e);


return tempFile.getAbsolutePath();




  1. If there is a need to include only specific fields then instead of exclude() in step 2 include() could be used and specify the fields to be transformed to JSON
  2. In order to avoid using include() and exclude() during serialization step as it might be painful if the number of fields to be included or excluded are quite a lot then this API provides an annotation @JSON which could be used above all the parameters in the Api Pojo to be included in the JSON while @JSON(include = false)  would represent that field would not be included in the JSON
  3. The string format path returned is the place where the temp file of JSON format exist and this file can then be downloaded say from the web using the following method:


public static void generatePackage(String packageName, HttpServletRequest request, HttpServletResponse response) {

try {

// This package name is the String returned by the class JSONCreator

File file = new File(packageName);

FileInputStream inputStream = new FileInputStream(file);

// MIME Type for JSON File

String mimeType = “application/json”;

// set content attributes for the response


// set headers for the response

String headerKey = “Content-Disposition”;

String headerValue = String.format(“attachment; filename=%s”, packageName);

response.setHeader(headerKey, headerValue);

// get output stream of the response

OutputStream outStream = response.getOutputStream();

// fetching the size of the file created and setting that length in the response.

int fileSize = Long.valueOf(file.length()).intValue();


try {

// fetches the path of the file.

Path path = file.toPath();

// Copies all the bytes from a file to an output stream

Files.copy(path, outStream);

} catch (IOException e) {

LOGGER.error(“Error while copying the inputStream content to outputStream in PackageGenerator class”, e);

} finally {

// closing the streams to avoid memory issues.




} catch (Exception e) {

LOGGER.error(“Error while generating JSON File”, e);







Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s