Created
May 15, 2017 13:37
-
-
Save sermojohn/9e16e240aee733d9ad8318443576a696 to your computer and use it in GitHub Desktop.
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.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