How deserialize based on information available in the parent class - java

I am using Jackson to deserialize a number of different implementations of the Product interface. These product implementations have different fields, but all have an InsuredAmount field. This InsuredAmount class has a value field and an IAType field. The IAType is a marker interface with different enums as implementations.
Now here's the problem: The enum implementations of the IAType interface correspond to a certain implementation of the Product interface. How can I make a generic implementation and tell Jackson to find the correct implementation of thee IAType? Should I use a generic parameter on the Product and the IAType interface identifying the product implementation? Should I use a Productable functional interface on the classes identifying the product implementation? How can I tell Jackson to use that implementation?
I hope the code below clarifies the problem, I chose to implement a Productable interface here, but a bettere structure to handle this problem would also be welcome.
#JsonPropertyOrder({"type", "someInfo"})
public class InsuredAmount implements Productable, Serializable {
private static final long serialVersionUID = 1L;
private IAType type;
private String someInfo;
public InsuredAmount() {
}
public InsuredAmount(IAType typeA, String someInfo) {
this.type = typeA;
this.someInfo = someInfo;
}
/* This should be on the product level, but if I can solve this problem,
the next level will just be more of the same.
*/
#JsonIgnore
#Override
public Product getProduct() {
return Product.PROD_A;
}
// Getters, setters, equals, etc. omitted.
}
--
public interface Productable {
public Product getProduct();
}
--
public enum Product {
PROD_A, PROD_B;
}
--
#JsonDeserialize(using = IATypeDeserializer.class)
public interface IAType extends Productable {
}
--
public enum IATypeA implements IAType {
FOO, BAR;
#Override
public Product getProduct() {
return Product.PROD_A;
}
}
--
public class IATypeDeserializer extends StdDeserializer<IAType> {
private static final long serialVersionUID = 1L;
public IATypeDeserializer() {
this(null);
}
public IATypeDeserializer(Class<?> vc) {
super(vc);
}
#Override
public IAType deserialize(JsonParser parser, DeserializationContext context)
throws IOException, JsonProcessingException {
JsonNode node = parser.getCodec().readTree(parser);
/* How to find out that the class calling the deserialization is InsuredAmountA, which
has getProduct() method that returns PROD_A, and matches the IATypeA that also returns
PROD_A, so I know to deserialize IATypeA, instead of other implementations of the IAType
interface?
*/
return IATypeA.valueOf(node.asText());
}
}
--
public class InsuredAmountTest {
private final ObjectMapper mapper = new ObjectMapper();
#Test
public void test01() throws IOException {
InsuredAmount iaA = new InsuredAmount(IATypeA.FOO, "test it");
String json = mapper.writeValueAsString(iaA);
assertThat(json, is("{\"type\":\"FOO\",\"someInfo\":\"test it\"}"));
InsuredAmount iaA2 = mapper.readValue(json, InsuredAmount.class);
IAType type = iaA2.getType();
assertThat(type, is(IATypeA.FOO));
assertThat(type.getProduct(), is(Product.PROD_A));
assertThat(iaA, is(iaA2));
}
#Test
public void test02() throws IOException {
InsuredAmount iaA = new InsuredAmount(IATypeA.BAR, "test it");
String json = mapper.writeValueAsString(iaA);
assertThat(json, is("{\"type\":\"BAR\",\"someInfo\":\"test it\"}"));
InsuredAmount iaA2 = mapper.readValue(json, InsuredAmount.class);
assertThat(iaA, is(iaA2));
}
}

Jackson handles the serialization of enums with minimal fuss, so all you need to do is annotate the IAType field with #JsonTypeInfo:
#JsonTypeInfo(use = JsonTypeInfo.Id.MINIMAL_CLASS)
private IAType type;
Then a test:
public static void main(String[] args) throws IOException {
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(new InsuredAmount(IATypeA.FOO, "info"));
System.out.println(json);
InsuredAmount ia = mapper.readValue(json, InsuredAmount.class);
System.out.println("Type is: " + ia.getType());
}
results in the output:
{"type":[".IATypeA","FOO"],"someInfo":"info"}
Type is: FOO
To get a more compact representation you will have to use custom serialization. Assuming that there are no overlaps in your enum namespace, you can serialize the type field as the enum name.
The deserializer will need to know which types are available for construction, either by class path discovery or, as in the following example, simply hard-coding the references:
public class IATest {
public static class IATypeSerializer extends JsonSerializer<IAType> {
#Override
public void serialize(IAType value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
gen.writeString(((Enum) value).name());
}
}
public static class IATypeDeserializer extends JsonDeserializer<IAType> {
#Override
public IAType deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
String value = p.readValueAs(String.class);
try {
return IATypeA.valueOf(value);
} catch (IllegalArgumentException e) {
// fall through
}
try {
return IATypeB.valueOf(value);
} catch (IllegalArgumentException e) {
// fall through
}
throw new JsonMappingException(p, "Unknown type '" + value + "'");
}
}
public static void main(String[] args) throws IOException {
ObjectMapper mapper = new ObjectMapper();
// Register a module to handle serialization of IAType implementations
SimpleModule module = new SimpleModule();
module.addSerializer(IAType.class, new IATypeSerializer());
module.addDeserializer(IAType.class, new IATypeDeserializer());
mapper.registerModule(module);
// Test
String json = mapper.writeValueAsString(new InsuredAmount(IATypeA.FOO, "info"));
System.out.println(json);
InsuredAmount ia = mapper.readValue(json, InsuredAmount.class);
System.out.println("Type is: " + ia.getType());
}
}
Which outputs:
{"type":"FOO","someInfo":"info"}
Type is: FOO

I ended up with using JsonCreator annotation on a special constructor.
#JsonCreator
public InsuredAmountA(
#JsonProperty("type") String type,
#JsonProperty("someInfo") String someInfo) throws IOException {
switch (getProduct()) {
case PROD_A:
try {
this.type = IATypeA.valueOf(type);
break;
} catch (IllegalArgumentException ex) {
// Throw IOException in the default.
}
// case PROD_B:
// this.type = (IATypeB) typeA;
// break;
default:
throw new IOException(String.format("Cannot parse value %s as type.", type));
}
this.someInfo = someInfo;
}

You may look into direction of polymorphic deserialisation:
http://wiki.fasterxml.com/JacksonPolymorphicDeserialization
unsing custom type resolver

Related

Jackson Custom Deserializer for polymorphic objects and String literals as defaults

I'd like to deserialize an object from YAML with the following properties, using Jackson in a Spring Boot application:
Abstract class Vehicle, implemented by Boat and Car
For simplicity, imagine both have a name, but only Boat has also a seaworthy property, while Car has a top-speed.
mode-of-transport:
type: boat
name: 'SS Boatface'
seaworthy: true
----
mode-of-transport:
type: car`
name: 'KITT'
top-speed: 123
This all works fine in my annotated subclasses using #JsonTypeInfo and #JsonSubTypes!
Now, I'd like to create a shorthand using only a String value, which should create a Car by default with that name:
mode-of-transport: 'KITT'
I tried creating my own custom serializer, but got stuck on most of the relevant details. Please help me fill this in, if this is the right approach:
public class VehicleDeserializer extends StdDeserializer<Merger> {
/* Constructors here */
#Override
public Vehicle deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
if (/* it is an OBJECT */){
// Use the default polymorphic deserializer
} else if (/* it is a STRING */) {
Car car = new Car();
car.setName( /* the String value */ );
return car;
}
return ???; /* what to return here? */
}
}
I found these 2 answers for inspiration, but it looks like combining it with polymorphic types makes it more difficult: How do I call the default deserializer from a custom deserializer in Jackson and Deserialize to String or Object using Jackson
A few things are different than the solutions offered in those questions:
I am processing YAML, not JSON. Not sure about the subtle differences there.
I have no problem hardcoding the 'default' type for Strings inside my Deserializer, hopefully making it simpler.
This was actually easier than I thought to solve it. I got it working using the following:
Custom deserializer implementation:
public class VehicleDeserializer extends StdDeserializer<Vehicle> {
public VehicleDeserializer() {
super(Vehicle.class);
}
#Override
public Vehicle deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
if (jp.currentToken() == JsonToken.VALUE_STRING) {
Car car = new Car();
car.setName(jp.readValueAs(String.class));
return car;
}
return jp.readValueAs(Vehicle.class);
}
}
To avoid circular dependencies and to make the custom deserializer work with the polymorphic #JsonTypeInfo and #JsonSubTypes annotations I kept those annotations on the class level of Vehicle, but put the following annotations on the container object I am deserializing:
public class Transport {
#JsonDeserialize(using = VehicleDeserializer.class)
#JsonTypeInfo(use = JsonTypeInfo.Id.NONE)
private Vehicle modeOfTransport;
// Getter, setters
}
This means that by default a Vehicle is deserialized as a polymorphic object, unless explicitly specified to deserialize it using my custom deserializer. This deserializer will then in turn defer to the polymorphism if the input is not a String.
Hopefully this will help someone running into this issue :)
So there is a solution that requires you to handle the jackson errors using a DeserializationProblemHandler (since you want to parse the same type using different inputs, this is not achieved easily using regular means):
public class MyTest {
#Test
public void doTest() throws JsonParseException, JsonMappingException, IOException {
final ObjectMapper om = new ObjectMapper();
om.addHandler(new DeserializationProblemHandler() {
#Override
public Object handleMissingInstantiator(final DeserializationContext ctxt, final Class<?> instClass, final JsonParser p, final String msg) throws IOException {
if (instClass.equals(Car.class)) {
final JsonParser parser = ctxt.getParser();
final String text = parser.getText();
switch (text) {
case "KITT":
return new Car();
}
}
return NOT_HANDLED;
}
#Override
public JavaType handleMissingTypeId(final DeserializationContext ctxt, final JavaType baseType, final TypeIdResolver idResolver, final String failureMsg) throws IOException {
// if (baseType.isTypeOrSubTypeOf(Vehicle.class)) {
final JsonParser parser = ctxt.getParser();
final String text = parser.getText();
switch (text) {
case "KITT":
return TypeFactory.defaultInstance().constructType(Car.class);
}
return super.handleMissingTypeId(ctxt, baseType, idResolver, failureMsg);
}
});
final Container objectValue = om.readValue(getObjectJson(), Container.class);
assertTrue(objectValue.getModeOfTransport() instanceof Car);
final Container stringValue = om.readValue(getStringJson(), Container.class);
assertTrue(stringValue.getModeOfTransport() instanceof Car);
}
private String getObjectJson() {
return "{ \"modeOfTransport\": { \"type\": \"car\", \"name\": \"KITT\", \"speed\": 1}}";
}
private String getStringJson() {
return "{ \"modeOfTransport\": \"KITT\"}";
}
}
class Container {
private Vehicle modeOfTransport;
public Vehicle getModeOfTransport() {
return modeOfTransport;
}
public void setModeOfTransport(final Vehicle modeOfTransport) {
this.modeOfTransport = modeOfTransport;
}
}
#JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type", visible = true)
#JsonSubTypes({
#Type(name = "car", value = Car.class)
})
abstract class Vehicle {
protected String type;
protected String name;
public String getType() {
return type;
}
public void setType(final String type) {
this.type = type;
}
public String getName() {
return name;
}
public void setName(final String name) {
this.name = name;
}
}
#JsonTypeName("car")
class Car extends Vehicle {
private int speed;
public int getSpeed() {
return speed;
}
public void setSpeed(final int speed) {
this.speed = speed;
}
}
Note that I used JSON, not YAML, and you need to add your other subtypes as well.

Jackson - How to replace serialized Map

I need to serialize a graph to JSON containing List and Map. Each map instance contains a UUID field. The graph can contain more than one Map instance with the same UUID. Maps with the same UUID are considered identical.
During Serialization, I would like to replace map instances that have a previously been serialized by only their UUID.
What is the best way to achieve that with Jackson?
Thanks
You can implement a custom serializer for your graph class.
You have to extend StdSerializer and override
#Override
public void serialize(T value, JsonGenerator jgen, SerializerProvider provider)
throws IOException, JsonProcessingException
When you did that you need to let jackson know about your serializer. You can achieve that by annotate your graph class with #JsonSerialize(using = CustomSerializer.class) or you could register a new module containing the custom serializer.
Below is the working solution I came up with.
However, is there a more elegant way to get a lifecycle hook on top-level serialize calls (which is needed to re-init the custom serializer)?
Also, I'm not convinced that keeping track of visited objects per thread, using ThreadLocal, is the best solution. Any advices?
Thanks
public class IdentifiableSerializerTest {
public static void main(String[] args) throws JsonProcessingException {
ObjectMapper mapper = createObjectMapper();
test(mapper);
}
interface Identifiable {
Long getId();
}
public static ObjectMapper createObjectMapper() {
ObjectMapper mapper = new ObjectMapper();
// disable quoting - for testing purpose
mapper.configure(JsonGenerator.Feature.QUOTE_FIELD_NAMES, false);
mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
// register serializer for Identifiable type
SimpleModule module = new SimpleModule();
module.addSerializer(Identifiable.class, new IdentifiableSerializer(mapper.writer()));
mapper.registerModule(module);
// lifecycle hook to re-init IdentifiableSerializer on root-level serialize calls
mapper.setSerializerProvider(new IdentifiableSerializerProvider());
return mapper;
}
/**
* This class serves to intercept root-level serialize calls in order to
* clean the map of visited objects, see {#link IdentifiableSerializer#visited}.
*
* TODO: this seems lot of code just to get a hook on root-level serialize calls...
*/
public static class IdentifiableSerializerProvider extends DefaultSerializerProvider {
public IdentifiableSerializerProvider() { super(); }
protected IdentifiableSerializerProvider(SerializerProvider src, SerializationConfig config, SerializerFactory f) {
super(src, config, f);
}
#Override
public DefaultSerializerProvider createInstance(SerializationConfig config, SerializerFactory f) {
return new IdentifiableSerializerProvider(this, config, f);
}
#Override
public void serializeValue(JsonGenerator gen, Object value) throws IOException {
IdentifiableSerializer.reset();
super.serializeValue(gen, value);
}
}
public static class IdentifiableSerializer extends JsonSerializer<Identifiable> {
private static ThreadLocal<Set> visited = new ThreadLocal<Set>() {
#Override
protected Set initialValue() {
return new HashSet();
}
};
public static void reset() {
visited.get().clear();
}
private final ObjectWriter delegate;
public IdentifiableSerializer(ObjectWriter delegate) {
this.delegate = delegate;
}
#Override
public void serialize(Identifiable value, JsonGenerator jgen, SerializerProvider provider) throws IOException {
Long id = value.getId();
Set seen = visited.get();
if (seen.contains(id)) {
jgen.writeStartObject();
jgen.writeNumberField("#REF", id);
jgen.writeEndObject();
}
else {
seen.add(id);
delegate.writeValue(jgen, value);
}
}
}
static class IdentifiableMap extends HashMap implements Identifiable {
static long counter = 0;
Long id = counter++;
{
put("#ID", id);
}
#Override
public Long getId() {
return id;
}
}
public static void test(ObjectMapper mapper) throws JsonProcessingException {
Map myMap = new IdentifiableMap() {{
put("key1", 1);
put("key2", 2);
put("key3", 3);
}};
List<Map> myList = Arrays.asList(myMap, myMap);
String expected = "[{key1:1,key2:2,key3:3,#ID:0},{#REF:0}]";
String actual = mapper.writeValueAsString(myList);
Assert.assertEquals(expected, actual);
System.out.println("SUCCESS");
}
}

Spring JSON Serializer and Deserializer is not getting called

I have written custom serializer and deserializer for com.google.common.collect.Table class. But it is not getting called while persisting that object in MongoDB. I am using Spring 4, Spring-MongoDB 1.9 and Jackson 2.8.4. Below are the class and configuration. Could you please let me know what's wrong with this. I want these class to be called while persisting and retrieving from MongoDB.
public class TableSeserializer extends StdSerializer<Table> {
/**
*
*/
private static final long serialVersionUID = 1L;
public TableSeserializer() {
this(Table.class);
}
public TableSeserializer(Class<Table> t) {
super(t);
}
#SuppressWarnings("unchecked")
#Override
public void serialize(Table value, JsonGenerator gen, SerializerProvider provider)
throws IOException {
gen.writeStartObject();
value.rowMap().forEach((i,map) ->{
try {
gen.writeNumber((int)i);
((Map)map).forEach((k,v)->{
try {
gen.writeStartObject();
Object object = ((Map)map).get(k);
if (object instanceof HTMLInputTag) {
HTMLInputTag inputTag = (HTMLInputTag) object;
gen.writeObjectField(inputTag.getId(),inputTag);
}else{
gen.writeObjectField(object.toString(),object);
}
gen.writeEndObject();
} catch (IOException e) {
e.printStackTrace();
}
});
} catch (IOException e) {
e.printStackTrace();
}
});
gen.writeEndObject();
}
}
public class TableDeserializer extends StdDeserializer<Table<Integer, String, HTMLInputTag>> {
/**
*
*/
private static final long serialVersionUID = 1L;
protected TableDeserializer(Class<?> vc) {
super(vc);
}
public TableDeserializer() {
this(null);
}
#Override
public Table<Integer, String, HTMLInputTag> deserialize(JsonParser jsonparser, DeserializationContext ctxt)
throws IOException, JsonProcessingException {
String data = jsonparser.getText();
ObjectMapper mapper = new ObjectMapper();
JsonNode node = mapper.readTree(data);
return null;
}
}
Spring configuration
#Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
SimpleModule module = new SimpleModule();
module.addSerializer(Table.class, new TableSeserializer());
module.addDeserializer(Table.class, new TableDeserializer());
Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder().modules(module);
converters.add(jacksonConverter(builder));
}
#Bean
MappingJackson2HttpMessageConverter jacksonConverter(Jackson2ObjectMapperBuilder builder) {
return new MappingJackson2HttpMessageConverter(builder.build());
}
Annotation in class
public class OrganizationAttributeMetaData extends CommonDomainAttributes implements Cloneable, Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private String attributeName;
private int orgid;
private String uniquecode; //3 Character unique code to uniquely identify
#JsonDeserialize(using=TableDeserializer.class)
#JsonSerialize(using=TableSeserializer.class)
Table<Integer, String, HTMLInputTag> htmlAttributes = null; //row,identifier and HTML
}
You really mixed some things ;) MongoDB indeed stores data in JSON-like format (BSON - Binary JSON) but it has nothing to do with Jackson - which is used (like the way you showed) to serialize/deserialize objects sent over HTTP.
In Spring Data MongoDB you need to implement and configure custom converters. More about that can be read here.

Handle Polymorphic with StdDeserializer Jackson 2.5

I have three classes which inherits from a super class (SensorData)
#JsonDeserialize(using = SensorDataDeserializer.class)
public abstract class SensorData {
}
public class HumiditySensorData extends SensorData {
}
public class LuminositySensorData extends SensorData {
}
public class TemperatureSensorData extends SensorData {
}
I want convert a json input into one of this classes depending on a parameter. I'm trying to use Jackson StdDeserializer and I create a custom deserializer
#Component
public class SensorDataDeserializer extends StdDeserializer<SensorData> {
private static final long serialVersionUID = 3625068688939160875L;
#Autowired
private SensorManager sensorManager;
private static final String discriminator = "name";
public SensorDataDeserializer() {
super(SensorData.class);
SpringBeanProvider.getInstance().autowireBean(this);
}
#Override
public SensorData deserialize(JsonParser parser,
DeserializationContext context) throws IOException,
JsonProcessingException {
ObjectMapper mapper = (ObjectMapper) parser.getCodec();
ObjectNode root = (ObjectNode) mapper.readTree(parser);
ObjectNode sensor = (ObjectNode) root.get("data");
String type = root.get(discriminator).asText();
Class<? extends SensorData> clazz = this.sensorManager
.getCachedSensorsMap().get(type).sensorDataClass();
if (clazz == null) {
// TODO should throw exception
return null;
}
return mapper.readValue(sensor.traverse(), clazz);
}
}
My problem is that when I determine the correct type to mapping the concrete class, the mapper call again to the custom StdDeserializer. So I need a way
to broke the cycle when I have the correct type. The stacktrace is the next one
java.lang.NullPointerException
at com.hp.psiot.mapping.SensorDataDeserializer.deserialize(SensorDataDeserializer.java:38)
at com.hp.psiot.mapping.SensorDataDeserializer.deserialize(SensorDataDeserializer.java:1)
at com.fasterxml.jackson.databind.ObjectMapper._readValue(ObjectMapper.java:3532)
at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:1868)
at com.hp.psiot.mapping.SensorDataDeserializer.deserialize(SensorDataDeserializer.java:47)
at com.hp.psiot.mapping.SensorDataDeserializer.deserialize(SensorDataDeserializer.java:1)
at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:3560)
at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2660)
at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.readJavaType(AbstractJackson2HttpMessageConverter.java:205)
at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.read(AbstractJackson2HttpMessageConverter.java:200)
at org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodArgumentResolver.readWithMessageConverters (AbstractMessageConverterMethodArgumentResolver.java:138)
at org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor.readWithMessageConverters(RequestResponseBodyMethodProcessor.java:184)
at org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor.resolveArgument(RequestResponseBodyMethodProcessor.java:105)
An example of input
{
"name":"temperature",
"data": {
"value":20
}
}
I only include the stacktrace to show that the mapper is calling again to the deserializer. The reason for the nullPointerException is that when the second the ObjectMapper is called the input is
"value":20
So, An exception is threw because we don't have the information to determine the type and it doesn't check if the input is correct
I want to avoid using JsonSubTypes and JsonTypeInfo if it's posible.
Thanks in advance!
Partial solution
In my case the SensorData is wrapped in other class (ServiceData)
class ServiceData {
#JsonDeserialize(using = SensorDataDeserializer.class)
List<SensorData> sensors;
}
So, I get rid of JsonDeserializer in SensorData class and put it in the field avoiding the cycle. The solution isn't the best, but in my case it helps me. But in the case that the class isn't wrapped in another one we still have the same problem.
Note that if you have a Collection and you annotate with JsonDeserialize that field you have to handle all the collection. Here is the modification
in my case
#Component
public class SensorDataDeserializer extends StdDeserializer<List<SensorData>> {
private static final long serialVersionUID = 3625068688939160875L;
#Autowired
private SensorManager sensorManager;
private static final String discriminator = "name";
public SensorDataDeserializer() {
super(SensorData.class);
SpringBeanProvider.getInstance().autowireBean(this);
}
#Override
public List<SensorData> deserialize(JsonParser parser,
DeserializationContext context) throws IOException,
JsonProcessingException {
try {
ObjectMapper mapper = (ObjectMapper) parser.getCodec();
ArrayNode root = (ArrayNode) mapper.readTree(parser);
int size = root.size();
List<SensorData> sensors = new ArrayList<SensorData>();
for (int i = 0; i < size; ++i) {
ObjectNode sensorHead = (ObjectNode) root.get(i);
ObjectNode sensorData = (ObjectNode) sensorHead.get("data");
String tag = sensorHead.get(discriminator).asText();
Class<? extends SensorData> clazz = this.sensorManager
.getCachedSensorsMap().get(tag).sensorDataClass();
if (clazz == null) {
throw new InvalidJson("unbound sensor");
}
SensorData parsed = mapper.readValue(sensorData.traverse(),
clazz);
if (parsed == null) {
throw new InvalidJson("unbound sensor");
}
sensors.add(parsed);
}
return sensors;
} catch (Throwable e) {
throw new InvalidJson("invalid data");
}
}
}
Hope it helps someone :)
Why don't you just use #JsonTypeInfo? Polymorphic handling is the specific use case for it.
In this case, you would want to use something like:
#JsonTypeInfo(use=Id.NAME, include=As.PROPERTY, property="name")
#JsonSubTypes({ HumiditySensorData.class, ... }) // or register via mapper
public abstract class SensorData { ... }
#JsonTypeName("temperature")
public class TemperaratureSensorData extends SensorData {
public TemperaratureSensorData(#JsonProperty("data") JsonNode data) {
// extract pieces out
}
}
which would handle resolution from 'name' into sub-type, bind contents of 'data' as JsonNode (or, if you prefer can use Map or Object or whatever type matches).

Jackson dynamic property names

I would like serialize an object such that one of the fields will be named differently based on the type of the field. For example:
public class Response {
private Status status;
private String error;
private Object data;
[ getters, setters ]
}
Here, I would like the field data to be serialized to something like data.getClass.getName() instead of always having a field called data which contains a different type depending on the situation.
How might I achieve such a trick using Jackson?
I had a simpler solution using #JsonAnyGetter annotation, and it worked like a charm.
import java.util.Collections;
import java.util.Map;
public class Response {
private Status status;
private String error;
#JsonIgnore
private Object data;
[getters, setters]
#JsonAnyGetter
public Map<String, Object> any() {
//add the custom name here
//use full HashMap if you need more than one property
return Collections.singletonMap(data.getClass().getName(), data);
}
}
No wrapper needed, no custom serializer needed.
Using a custom JsonSerializer.
public class Response {
private String status;
private String error;
#JsonProperty("p")
#JsonSerialize(using = CustomSerializer.class)
private Object data;
// ...
}
public class CustomSerializer extends JsonSerializer<Object> {
public void serialize(Object value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException {
jgen.writeStartObject();
jgen.writeObjectField(value.getClass().getName(), value);
jgen.writeEndObject();
}
}
And then, suppose you want to serialize the following two objects:
public static void main(String... args) throws Exception {
ObjectMapper mapper = new ObjectMapper();
Response r1 = new Response("Error", "Some error", 20);
System.out.println(mapper.writeValueAsString(r1));
Response r2 = new Response("Error", "Some error", "some string");
System.out.println(mapper.writeValueAsString(r2));
}
The first one will print:
{"status":"Error","error":"Some error","p":{"java.lang.Integer":20}}
And the second one:
{"status":"Error","error":"Some error","p":{"java.lang.String":"some string"}}
I have used the name p for the wrapper object since it will merely serve as a placeholder. If you want to remove it, you'd have to write a custom serializer for the entire class, i.e., a JsonSerializer<Response>.
my own solution.
#Data
#EqualsAndHashCode
#ToString
#JsonSerialize(using = ElementsListBean.CustomSerializer.class)
public class ElementsListBean<T> {
public ElementsListBean()
{
}
public ElementsListBean(final String fieldName, final List<T> elements)
{
this.fieldName = fieldName;
this.elements = elements;
}
private String fieldName;
private List<T> elements;
public int length()
{
return (this.elements != null) ? this.elements.size() : 0;
}
private static class CustomSerializer extends JsonSerializer<Object> {
public void serialize(Object value, JsonGenerator jgen, SerializerProvider provider) throws IOException,
JsonProcessingException
{
if (value instanceof ElementsListBean) {
final ElementsListBean<?> o = (ElementsListBean<?>) value;
jgen.writeStartObject();
jgen.writeArrayFieldStart(o.getFieldName());
for (Object e : o.getElements()) {
jgen.writeObject(e);
}
jgen.writeEndArray();
jgen.writeNumberField("length", o.length());
jgen.writeEndObject();
}
}
}
}
You can use the annotation JsonTypeInfo, which tell Jackson exactly that and you don't need to write a custom serializer. There's various way to include this information, but for your specific question you'd use As.WRAPPER_OBJECT and Id.CLASS. For example:
public static class Response {
private Status status;
private String error;
#JsonTypeInfo(include = As.WRAPPER_OBJECT, use = Id.CLASS)
private Object data;
}
This, however, will not work on primitive type, such as a String or Integer. You don't need that information for primitives anyways, since they are natively represented in JSON and Jackson knows how to handle them. The added bonus with using the annotation is that you get deserialization for free, if you ever need it. Here's an example:
public static void main(String[] args) throws Exception {
ObjectMapper mapper = new ObjectMapper();
Response r1 = new Response("Status", "An error", "some data");
Response r2 = new Response("Status", "An error", 10);
Response r3 = new Response("Status", "An error", new MyClass("data"));
System.out.println(mapper.writeValueAsString(r1));
System.out.println(mapper.writeValueAsString(r2));
System.out.println(mapper.writeValueAsString(r3));
}
#JsonAutoDetect(fieldVisibility=Visibility.ANY)
public static class MyClass{
private String data;
public MyClass(String data) {
this.data = data;
}
}
and the result:
{"status":"Status","error":"An error","data":"some data"}
{"status":"Status","error":"An error","data":10}
{"status":"Status","error":"An error","data":{"some.package.MyClass":{"data":"data"}}}
Based on #tlogbon response,
Here is my solution to wrap a List of Items with a specific/dynamic filed name
public class ListResource<T> {
#JsonIgnore
private List<T> items;
#JsonIgnore
private String fieldName;
public ListResource(String fieldName, List<T> items) {
this.items = items;
this.fieldName = fieldName;
}
#JsonAnyGetter
public Map<String, List<T>> getMap() {
return Collections.singletonMap(fieldName, items);
}

Categories

Resources