Thursday, 17 March 2022

Jackson: Write object json to a file

ObjectMapper class provides ‘writeValue’ method, which is used to serialize any Java value as JSON output, written to File provided.

 

Signature

public void writeValue(File resultFile, Object value)

 

Example

objectMapper.writeValue(new File(filePath), emp);

 


 

Find the below working application.

 

WriteJsonToAFile.java

package com.sample.app;

import java.io.File;
import java.io.IOException;

import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class WriteJsonToAFile {

	public static class Employee {
		private int id;
		private String name;

		public Employee() {
		}

		public Employee(int id, String name) {
			this.id = id;
			this.name = name;
		}

		public int getId() {
			return id;
		}

		public void setId(int id) {
			this.id = id;
		}

		public String getName() {
			return name;
		}

		public void setName(String name) {
			this.name = name;
		}

	}

	public static void main(String[] args) throws JsonGenerationException, JsonMappingException, IOException {
		Employee emp = new Employee(1, "Krishna");

		ObjectMapper objectMapper = new ObjectMapper();
		String filePath = "/Users/Shared/examples/demo.json";

		objectMapper.writeValue(new File(filePath), emp);
	}

}

Run above application and open demo.json file, you will see below content.

$cat demo.json {"id":1,"name":"Krishna"}



Previous                                                    Next                                                    Home

No comments:

Post a Comment