Skip to content

Instantly share code, notes, and snippets.

@sermojohn
Created May 15, 2017 13:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sermojohn/9e16e240aee733d9ad8318443576a696 to your computer and use it in GitHub Desktop.
Save sermojohn/9e16e240aee733d9ad8318443576a696 to your computer and use it in GitHub Desktop.
import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Assert;
import org.junit.Test;
import java.io.IOException;
import java.util.Collections;
import java.util.Map;
public class JacksonPolymorphismIssueTests {
@Test
public void testUnsuccessfulSerialization() throws IOException
{
ObjectMapper mapper = new ObjectMapper();
Dog dog = new Dog();
Map<String, Map<String, Object>> incorrectSerialization = mapper.readValue(mapper.writeValueAsString(Collections.singletonMap("value", dog)), Map.class);
Map<String, Object> unwrappedObject = incorrectSerialization.get("value");
Assert.assertTrue(unwrappedObject.containsKey("type"));
}
@Test
public void testSuccessfulSerialization() throws IOException {
ObjectMapper mapper = new ObjectMapper();
Dog dog = new Dog();
Map<String, Object> correctSerialization = mapper.readValue(mapper.writeValueAsString(dog), Map.class);
Assert.assertTrue(correctSerialization.containsKey("type"));
}
@JsonTypeInfo(use=JsonTypeInfo.Id.NAME, include=JsonTypeInfo.As.PROPERTY, property="type")
@JsonSubTypes({
@JsonSubTypes.Type(value= Dog.class, name="dog")
})
interface IPet
{
public Long getId();
public String getPetMakes();
}
class Dog implements IPet
{
@Override
public String getPetMakes()
{
return "Wuff!";
}
@Override
public Long getId()
{
return 777L;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment