Read and Write JSON with File

Write JSON to file

package com.json.demo4_27;

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

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class WriteJsonToFile {
	public static void main(String[] args) throws IOException {
		ObjectMapper objectMapper = new ObjectMapper();
		Map<String,Object> mapJson = new LinkedHashMap<>();
		mapJson.put("key1","value1");
		mapJson.put("key2","value2");
		mapJson.put("key3","value3");
		mapJson.put("booleanTrue",true);
		mapJson.put("booleanFalse",false);
		mapJson.put("Integer One",1);
		mapJson.put("Integer Two",2);
		mapJson.put("Object",new Person(1,"Tyson",60));
		mapJson.put("NullValue",null);
		mapJson.put("Array",new String[] {"One","Two","Three"});
		mapJson.put("ArrayOfObjects",new Person[] {new Person(1,"Tyson",60),new Person(2,"Justin",70)});
		System.out.println(objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(mapJson));
		//Writing the json to file
		objectMapper.writerWithDefaultPrettyPrinter().writeValue(new File("map.json"),mapJson);
	}
}
class Person {
	@JsonProperty(value = "Person ID")
	int id;
	@JsonProperty(value = "Person Name")
	String name;
	@JsonProperty(value = "Person Age")
	int age;
	
	Person(int id,String name,int age){
		this.id = id;
		this.name = name;
		this.age = age;
	}
	
	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 int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
}

Read JSON from File

package com.json.demo5_28;

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

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class DatabindJsonToObjectFromFile {
	public static void main(String[] args) throws JsonParseException, JsonMappingException, IOException {
		String jsonFile = "/home/tyson/Documents/Application-Data/eclipse-workspace/Demo/lib/map.json";
		ObjectMapper objectMapper = new ObjectMapper();
		ClassLoader classLoader = DatabindJsonToObjectFromFile.class.getClassLoader();
		Map<String,Object> map = objectMapper.readValue(new File(classLoader.getResource("map.json").getFile()), 
				new TypeReference<Map<String,Object>>(){});
		System.out.println(map);
	}
}

Leave a Comment