JSON databinding with Jackson Annotations

package com.json.demo2_25;

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

/**
 * Binding an Object to a JSON using Annotations
 * @author tyson
 *
 */
public class DataBindingWithAnnotations {
	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 {
	@JsonProperty(value = "Person ID")
	int id;
	@JsonProperty(value = "Person Name")
	String name;
	@JsonProperty(value = "Person Age")
	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