Skip to content

Instantly share code, notes, and snippets.

@sscovil
Created January 31, 2014 16:44
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 sscovil/8735923 to your computer and use it in GitHub Desktop.
Save sscovil/8735923 to your computer and use it in GitHub Desktop.
This is the incorrect way to perform polymorphic JSON deserialization using Jackson's ObjectMapper. The correct way can be seen here: https://gist.github.com/sscovil/8788339. This gist was created for the following StackOverflow question: http://stackoverflow.com/questions/21485923/java-jackson-polymorphic-json-deserialization-of-an-object-with-…
import org.codehaus.jackson.annotate.JsonSubTypes;
import org.codehaus.jackson.annotate.JsonTypeInfo;
import org.codehaus.jackson.annotate.JsonTypeName;
import org.codehaus.jackson.map.ObjectMapper;
import org.testng.Assert;
import org.testng.annotations.Test;
import java.io.IOException;
public class IntegrationTests {
@Test
public void deserializeJsonSucceeds() {
Asset asset = deserializeJson("{ \"type\": \"document\", \"properties\": { \"source\": \"foo\", \"proxy\": \"bar\" } }");
Assert.assertTrue(asset.getProperties() instanceof DocumentAssetProperties);
}
public Asset deserializeJson(String json) {
ObjectMapper mapper = new ObjectMapper();
try {
return mapper.readValue(json, Asset.class);
}
catch(IOException e) {
Assert.fail("Could not deserialize JSON.", e);
}
return null;
}
public class Asset {
private String type;
private AssetProperties properties;
public String getType() { return type; }
public void setType(String type) { this.type = type; }
public AssetProperties getProperties() { return properties; }
public void setProperties(AssetProperties properties) { this.properties = properties; }
}
@JsonTypeInfo(
use = JsonTypeInfo.Id.NAME,
include = JsonTypeInfo.As.PROPERTY,
property = "type"
)
@JsonSubTypes({
@JsonSubTypes.Type(value = ImageAssetProperties.class, name = "image"),
@JsonSubTypes.Type(value = DocumentAssetProperties.class, name = "document")
})
public interface AssetProperties {
String getSource();
AssetProperties setSource(String source);
String getProxy();
AssetProperties setProxy(String proxy);
}
@JsonTypeName("document")
public class DocumentAssetProperties implements AssetProperties {
private String source;
private String proxy;
public String getSource() { return source; }
public DocumentAssetProperties setSource(String source) {
this.source = source;
return this;
}
public String getProxy() { return proxy; }
public DocumentAssetProperties setProxy(String proxy) {
this.proxy = proxy;
return this;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment