Created
November 19, 2012 20:07
-
-
Save ihr/4113543 to your computer and use it in GitHub Desktop.
Jackson Databind NPE show case
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import com.fasterxml.jackson.annotation.*; | |
import com.fasterxml.jackson.core.JsonFactory; | |
import com.fasterxml.jackson.core.JsonParser; | |
import com.fasterxml.jackson.databind.ObjectMapper; | |
import org.hamcrest.core.IsEqual; | |
import org.junit.Assert; | |
import org.junit.Test; | |
import java.io.IOException; | |
public class JacksonTest { | |
@JsonIgnoreProperties(ignoreUnknown = true) | |
@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = "_class") | |
@JsonSubTypes({ | |
@JsonSubTypes.Type(Cat.class), | |
@JsonSubTypes.Type(Dog.class) | |
}) | |
public static abstract class Animal { | |
public final static String ID = "id"; | |
private String id; | |
public Animal() { | |
} | |
@JsonCreator | |
public Animal(@JsonProperty(ID) String id) { | |
this.id = id; | |
} | |
@JsonProperty(ID) | |
public String getId() { | |
return id; | |
} | |
} | |
@JsonIgnoreProperties(ignoreUnknown = true) | |
public static class Cat extends Animal { | |
public Cat() { | |
super(); | |
} | |
@JsonCreator | |
public Cat(@JsonProperty(ID) String id) { | |
super(id); | |
} | |
} | |
@JsonIgnoreProperties(ignoreUnknown = true) | |
public static class Dog extends Animal { | |
public Dog() { | |
super(); | |
} | |
@JsonCreator | |
public Dog(@JsonProperty(ID) String id) { | |
super(id); | |
} | |
} | |
@JsonIgnoreProperties(ignoreUnknown = true) | |
public static class AnimalWrapper { | |
public static final String ANIMAL = "animal"; | |
private Animal animal; | |
@JsonCreator | |
public AnimalWrapper(@JsonProperty(ANIMAL) Animal animal) { | |
this.animal = animal; | |
} | |
@JsonProperty(ANIMAL) | |
public Animal getAnimal() { | |
return animal; | |
} | |
} | |
@Test | |
public void shouldRun() throws IOException { | |
ObjectMapper mapper = new ObjectMapper(); | |
JsonFactory factory = mapper.getJsonFactory(); | |
String id = "nice dogy"; | |
String serializedDog = mapper.writeValueAsString(new AnimalWrapper(new Dog(id))); | |
JsonParser parser = factory.createJsonParser(serializedDog); | |
AnimalWrapper wrapper = parser.readValueAs(AnimalWrapper.class); | |
Assert.assertThat(wrapper.getAnimal().getId(), IsEqual.equalTo(id)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment