Java json – jackson Mix- In Annotations

Also see json simple org.json

Annotations are a great way to manage serialization and deserialization in Jackson. However, what do you do if you want to annotate a third party class, or if you dont want to tightly couple your POJOs to jackson annotations. This is where Mix-in comes into play. You define a mix-in abstract class that is kind of a proxy to the actual class. Annotations are then definied over this proxy class

Jackson Mix-In Example

package com.studytrails.json.jackson;

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 SerializeExample3 {
	public static void main(String[] args) throws JsonGenerationException, JsonMappingException, IOException {
		ObjectMapper mapper = new ObjectMapper();
		mapper.addMixInAnnotations(Bird.class, BirdMixIn.class);
		Bird bird = new Bird("scarlet Ibis");
		bird.setSound("eee");
		bird.setHabitat("water");

		mapper.writerWithDefaultPrettyPrinter().writeValue(new File("bird.json"), bird);
	}

}


The Bird class

package com.studytrails.json.jackson;

public class Bird {

	private String name;
	private String sound;
	private String habitat;

	public Bird(String name) {
		this.name = name;
	}

	public String getName() {
		return name;
	}

	public String getSound() {
		return sound;
	}

	public String getHabitat() {
		return habitat;
	}

	public void setSound(String sound) {
		this.sound = sound;
	}

	public void setHabitat(String habitat) {
		this.habitat = habitat;
	}

	@Override
	public String toString() {
		return "Bird [name=" + name + ", sound=" + sound + ", habitat=" + habitat + "]";
	}
	
	

}

The Mix-in class

package com.studytrails.json.jackson;

import com.fasterxml.jackson.annotation.JsonProperty;

public abstract class BirdMixIn {
	BirdMixIn(@JsonProperty("name") String name) {
	};

	@JsonProperty("sound")
	abstract String getSound();

	@JsonProperty("habitat")
	abstract String getHabitat();
}

Leave a Reply

Your email address will not be published. Required fields are marked *