How to Convert Java Object to/from JSON (Jackson)


In this example we will show how to convert java object to/from JSON (Jackson).

Source Code

1) Example.class

package com.beginner.examples;

import java.io.File;
import java.io.IOException;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;

public class JsonConvert {

	public static void main(String[] args) throws JsonGenerationException, JsonMappingException, IOException {
		
		Person person = createPerson();     
		File file = new File("E:tmptest.json");   
		ObjectMapper objectMapper = new ObjectMapper();
		objectMapper.writeValue(file, person);
		String jsonInString = objectMapper.writeValueAsString(person);
		System.out.println(jsonInString);
	}
	
	public static Person createPerson() {
		Person person = new Person();
		person.setName("Alice");
		person.setAge(18);
		person.setNum(1);
		
		return person;
	}
	

}

2) Person.class

package com.beginner.examples;

public class Person {
	private String name;
	private int age;
	private int num;
	
	public Person() {};
	
	public Person(String name, int ager, int num) {
		this.name = name;
		this.age = age;
		this.num = num;
	}
	
	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;
	}
	
	public int getNum() {
		return num;
	}
	public void setNum(int num) {
		this.num = num;
	}
}

Output:

output:{"name":"Alice","age":18,"num":1}

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments