JSON databinding in java

Converting java object to Json string

package com.json.demo1_24;

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

/**
 * Binding an Object to a JSON without Annotations
 * @author tyson
 *
 */
public class DataBinding {
	public static void main(String[] args) throws JsonProcessingException {
		ObjectMapper objectMapper = new ObjectMapper();
		Person tyson = new Person();
		tyson.setAge(99);
		tyson.setId(1);
		tyson.setName("Tyson Gill");
//		System.out.println(objectMapper.writeValueAsString(tyson));
		System.out.println(objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(tyson));
	}
}
class Person {
	int id;
	String name;
	int 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;
	}
}

Leave a Comment