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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | 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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | 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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | 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(); } |
Java json – jackson Mix- In Annotations
Thanks for great tutorials.
according to documentation “addMixInAnnotations()” method which returns void, is replaced by a fluent form of the method; addMixIn(Class, Class) which returns ObjectMapper; since 2.5.
This method is used in SerializeExample3 class above.