Jackson: Ignore whitespace in empty #XmlWrapperElement collection - java

Using Jackson and jackson-dataformat-xml 2.4.4, I'm trying to deserialize a XML document where a collection annotated with #XmlWrapperElement may have zero elements, but where the XML contains whitespace (in my case a line break). Jackson throws a JsonMappingException on this content with the message “Can not deserialize instance of java.util.ArrayList out of VALUE_STRING token”. I cannot change the way the XML is produced.
Example:
static class Outer {
#XmlElementWrapper
List<Inner> inners;
}
static class Inner {
#XmlValue
String foo;
}
ObjectMapper mapper = new XmlMapper().registerModules(new JaxbAnnotationModule());
String xml = "<outer><inners>\n</inners></outer>";
Outer outer = mapper.readValue(xml, Outer.class);
The following workarounds do not work:
Enabling DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY: In this case Jackson wants to instantiate a bogus instance of Inner using the whitespace as content.
Creating setters for this field for both String and the collection type. In this case I get a JsonMappingException (“Conflicting setter definitions for property "inners"”).
In a similar Stackoverflow question it is suggested to downgrade Jackson to 2.2.3. This does not fix the problem for me.
Any suggestions?
Edit: I can work around this issue by wrapping the CollectionDeserializer and checking for a whitespace token. This looks however very fragile to me, e.g. I had to override another method to rewrap the object. I can post the workaround, but a cleaner approach would be better.

A workaround for this problem is to wrap the standard CollectionDeserializer to return an empty collection for tokens containing whitespace and register the new Deserializer. I put the code into a Module so it can be registered easily:
import java.io.IOException;
import java.util.Collection;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.databind.BeanDescription;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.DeserializationConfig;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.deser.BeanDeserializerModifier;
import com.fasterxml.jackson.databind.deser.std.CollectionDeserializer;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.type.CollectionType;
public class XmlWhitespaceModule extends SimpleModule {
private static class CustomizedCollectionDeserialiser extends CollectionDeserializer {
public CustomizedCollectionDeserialiser(CollectionDeserializer src) {
super(src);
}
private static final long serialVersionUID = 1L;
#SuppressWarnings("unchecked")
#Override
public Collection<Object> deserialize(JsonParser jp, DeserializationContext ctxt)
throws IOException, JsonProcessingException {
if (jp.getCurrentToken() == JsonToken.VALUE_STRING
&& jp.getText().matches("^[\\r\\n\\t ]+$")) {
return (Collection<Object>) _valueInstantiator.createUsingDefault(ctxt);
}
return super.deserialize(jp, ctxt);
}
#Override
public CollectionDeserializer createContextual(DeserializationContext ctxt,
BeanProperty property) throws JsonMappingException {
return new CustomizedCollectionDeserialiser(super.createContextual(ctxt, property));
}
}
private static final long serialVersionUID = 1L;
#Override
public void setupModule(SetupContext context) {
super.setupModule(context);
context.addBeanDeserializerModifier(new BeanDeserializerModifier() {
#Override
public JsonDeserializer<?> modifyCollectionDeserializer(
DeserializationConfig config, CollectionType type,
BeanDescription beanDesc, JsonDeserializer<?> deserializer) {
if (deserializer instanceof CollectionDeserializer) {
return new CustomizedCollectionDeserialiser(
(CollectionDeserializer) deserializer);
} else {
return super.modifyCollectionDeserializer(config, type, beanDesc,
deserializer);
}
}
});
}
}
After that you can add it to your ObjectMapper like this:
ObjectMapper mapper = new XmlMapper().registerModule(new XmlWhitespaceModule());

Related

#JsonSerialize - How to create a wrapper at runtime and use default serialization for the object fields?

I want to add a wrapper which named is determined at runtime, because it depends of the class name (I could use #JsonRootName but I don't want to because I would have to use it on every sub class, which is not efficient).
I suppose I should use #JsonSerialize to override the default serializer, but I want that just to create the wrapper; I don't want to serialize the object fields myself (also I am in an abstract class, so I don't even know the fields of the sub class!). I don't care about them, I just care about the wrapper! So I would like the default serializer to handle those fields for me, or something like that.
#JsonSerialize(using = CustomSerializer.class)
public abstract class Request {
public static class CustomSerializer extends JsonSerializer<Request > {
#Override
public void serialize(Request request, JsonGenerator jgen, SerializerProvider provider) throws IOException {
// Doing my stuff to determine the wrapper name based on request.class.getSimpleName()
// Then what should I wright to serialize the fields?
// Basically I just want a function to generate the same json that the default serializer would generate!
// I tried the following, but obviously it gives a com.fasterxml.jackson.databind.JsonMappingException: Infinite recursion
jgen.writeObject(value);
// Same error for the function below
provider.defaultSerializeValue(value, jgen);
}
}
To create wrapper serialiser you need to use com.fasterxml.jackson.databind.ser.BeanSerializerModifier class. You can register it using com.fasterxml.jackson.databind.module.SimpleModule. Below example shows end-to-end solution how to do that:
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.BeanDescription;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationConfig;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.json.JsonMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.BeanSerializerModifier;
import com.fasterxml.jackson.databind.util.NameTransformer;
import java.io.IOException;
import java.util.UUID;
public class JsonPathApp {
public static void main(String[] args) throws Exception {
SimpleModule wrappersModule = new SimpleModule("requestWrapper");
wrappersModule.setSerializerModifier(new BeanSerializerModifier() {
#Override
public JsonSerializer<?> modifySerializer(SerializationConfig config, BeanDescription beanDesc, JsonSerializer<?> serializer) {
if (Request.class.isAssignableFrom(beanDesc.getBeanClass())) {
return new RequestWrapperJsonSerializer(serializer);
}
return serializer;
}
});
ObjectMapper mapper = JsonMapper.builder()
.enable(SerializationFeature.INDENT_OUTPUT)
.addModule(wrappersModule)
.build();
System.out.println(mapper.writeValueAsString(new Request1(1, "POST")));
System.out.println(mapper.writeValueAsString(new Request2(2, UUID.randomUUID())));
}
}
class RequestWrapperJsonSerializer extends JsonSerializer<Request> {
private final JsonSerializer baseSerializer;
public RequestWrapperJsonSerializer(JsonSerializer baseSerializer) {
this.baseSerializer = baseSerializer;
}
#Override
public void serialize(Request value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
gen.writeStartObject();
gen.writeFieldName(value.getClass().getSimpleName() + "Wrapper");
gen.writeStartObject();
baseSerializer.unwrappingSerializer(NameTransformer.NOP).serialize(value, gen, serializers);
gen.writeEndObject();
gen.writeEndObject();
}
}
abstract class Request {
private int id;
//constructor, getters, setters, toString
}
class Request1 extends Request {
private String body;
//constructor, getters, setters, toString
}
class Request2 extends Request {
private UUID uuid;
//constructor, getters, setters, toString
}
Above code prints:
{
"Request1Wrapper" : {
"id" : 1,
"body" : "POST"
}
}
{
"Request2Wrapper" : {
"id" : 2,
"uuid" : "dd4cccb5-1cf5-4dd4-8bc7-97cb101e5d7d"
}
}
Instead unwrappingSerializer method you can use serialize method and remove extra wrapping invocations.
Even though the solution I accepted is correct, I propose an other solution I got from a similar stackoverflow question, and which relies on a trick: make the class to custom-serialize a field of an other class (purely used for wrapping) and use #JsonSerialize on this field. The code is simpler, but you have to create and manipulate the wrapper class. See below:
public class RequestWrapper {
#JsonUnwrapped // Prevent the field from being wrap with its name: "request"
#JsonSerialize(using = RequestSerializer.class)
private final Request request;
private RequestWrapper(Request request) {
this.request= request;
}
public Request getRequest() {
return request;
}
public static class RequestSerializer extends JsonSerializer<Request> {
#Override
public boolean isUnwrappingSerializer() {
return true; // Indicates that we are creating an "unwrapping" serializer, because we added #JsonUnwrapped
}
#Override
public void serialize(Request request, JsonGenerator jgen, SerializerProvider provider) throws IOException {
jgen.writeObjectField(request.getClass().getSimpleName(), value);
}
}
}

Deserialize a Map from JAXB generated XML using Jackson

I need to deserialize some XMLs that are being generated using JAXB.
Due to some compliance issue, I have to only use Jackson for XML parsing.
I am getting below exception when trying to deserialize a class that has a Map
com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `java.lang.String` out of START_OBJECT token
at [Source: (StringReader); line: 40, column: 21] (through reference chain: FileConfig["otherConfigs"]->java.util.LinkedHashMap["entry"])
My code is as follows:
XML file:
.
.
.
<fileConfig>
<whetherNotify>false</whetherNotify>
<url>....some location....</url>
<includes>app.log</includes>
<fileType>...some string...</fileType>
<otherConfigs>
<entry>
<key>pathType</key>
<value>1</value>
</entry>
</otherConfigs>
</fileConfig>
.
.
.
FileConfig.java
public class FileConfig implements Serializable {
protected Boolean whetherNotify = false;
protected String url;
protected String includes;
protected FileType fileType;
private Map<String, String> otherConfigs = new HashMap<String, String>();
....getters and setters.....
}
Main.java
public class Main {
.
.
.
.
private static <T> T unmarshallFromXML(String xml, Class<T> parseToClass) throws IOException {
XmlMapper xmlMapper = new XmlMapper();
xmlMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.NONE);
xmlMapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);
xmlMapper.enable(SerializationFeature.INDENT_OUTPUT);
xmlMapper.setDefaultSetterInfo(JsonSetter.Value.forValueNulls(Nulls.AS_EMPTY));
xmlMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
xmlMapper.setDefaultUseWrapper(false);
xmlMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
T parsedObject = xmlMapper.readValue(xml, parseToClass);
return parsedObject;
}
}
Please suggest a method to successfully parse that map using Jackson.
By default Map is serialized to XML in:
...
<key>value</key>
<key1>value1</key1>
...
format. There is not entry element. You have two options:
Change model and instead of Map use List<Entry> type.
Implement custom deserializer for a Map type.
New model
You need to create Entry class:
class Entry {
private String key;
private String value;
// getters, setters, toString
}
and change property in FileConfig class to:
List<Entry> otherConfigs;
Custom map deserializer
See below example:
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class XmlApp {
public static void main(String[] args) throws Exception {
File xmlFile = new File("./test.xml");
XmlMapper xmlMapper = new XmlMapper();
FileConfig fileConfig = xmlMapper.readValue(xmlFile, FileConfig.class);
System.out.println(fileConfig);
}
}
class MapEntryDeserializer extends JsonDeserializer<Map<String, String>> {
#Override
public Map<String, String> deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
Map<String, String> map = new HashMap<>();
JsonToken token;
while ((token = p.nextToken()) != null) {
if (token == JsonToken.FIELD_NAME) {
if (p.getCurrentName().equals("entry")) {
p.nextToken();
JsonNode node = p.readValueAsTree();
map.put(node.get("key").asText(), node.get("value").asText());
}
}
}
return map;
}
}
class FileConfig {
protected Boolean whetherNotify = false;
protected String url;
protected String includes;
#JsonDeserialize(using = MapEntryDeserializer.class)
private Map<String, String> otherConfigs;
// getters, setters, toString
}
Above code prints:
FileConfig{whetherNotify=false, url='....some location....', includes='app.log', otherConfigs={pathType1=2, pathType=1}}

"Relaxed" fields names for Jackson

I'm working on Jackson configuration and I wonder if there is any option to deserialise different kinds of field patterns.
For example, I have an object:
class DeserializeIt {
String fieldOne;
String fieldOneAndHalf;
String fieldTwo;
String fieldThree;
String fieldFour;
//getters setters etc.
}
And I have below JSON payload:
{
"fieldOne" : "value1",
"field_ONE-and_Half": "value15",
"FIELD_TWO": "value2",
"FIELD_THREE" : "value3",
"field_four": "value4"
}
I would like to deserialize all these field names to camel case without an exception.
I tried to create my custom PropertyNamingStrategy but it goes from another direction: it does not convert delimitered fields to camel case, it tries to convert the objects fields and search for them in the parsed string.
And since I cannot pass a list of possible strings instead of one variation (fieldOne can become field-one, field_one, field-ONE etc.), this does not work.
Do you know what else could I configure for such a relaxed deserialization?
We need to extend com.fasterxml.jackson.databind.deser.BeanDeserializerModifier and com.fasterxml.jackson.databind.deser.BeanDeserializer which deserialises POJO classes. Below solution depends from version you are using because I copied some code from base class which is not ready for intercepting extra functionality. If you do not have any extra configuration for your POJO classes vanillaDeserialize method will be invoked and this one we will try to improve.
In other case you need to debug this deserialiser and updated other places if needed. Below solution uses version 2.9.8.
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.core.JsonTokenId;
import com.fasterxml.jackson.databind.BeanDescription;
import com.fasterxml.jackson.databind.DeserializationConfig;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.deser.BeanDeserializer;
import com.fasterxml.jackson.databind.deser.BeanDeserializerBase;
import com.fasterxml.jackson.databind.deser.BeanDeserializerModifier;
import com.fasterxml.jackson.databind.deser.SettableBeanProperty;
import com.fasterxml.jackson.databind.module.SimpleModule;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class JsonApp {
public static void main(String[] args) throws Exception {
File jsonFile = new File("./resource/test.json").getAbsoluteFile();
SimpleModule relaxedModule = new SimpleModule();
relaxedModule.setDeserializerModifier(new RelaxedBeanDeserializerModifier());
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(relaxedModule);
System.out.println(mapper.readValue(jsonFile, DeserializeIt.class));
}
}
class RelaxedBeanDeserializerModifier extends BeanDeserializerModifier {
#Override
public JsonDeserializer<?> modifyDeserializer(DeserializationConfig config, BeanDescription beanDesc, JsonDeserializer<?> deserializer) {
JsonDeserializer<?> base = super.modifyDeserializer(config, beanDesc, deserializer);
if (base instanceof BeanDeserializer) {
return new RelaxedBeanDeserializer((BeanDeserializer) base);
}
return base;
}
}
class RelaxedBeanDeserializer extends BeanDeserializer {
private Map<String, String> properties = new HashMap<>();
public RelaxedBeanDeserializer(BeanDeserializerBase src) {
super(src);
_beanProperties.forEach(property -> {
properties.put(property.getName().toLowerCase(), property.getName());
});
}
public Object deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
// common case first
if (p.isExpectedStartObjectToken()) {
if (_vanillaProcessing) {
return vanillaDeserialize(p, ctxt, p.nextToken());
}
// 23-Sep-2015, tatu: This is wrong at some many levels, but for now... it is
// what it is, including "expected behavior".
p.nextToken();
if (_objectIdReader != null) {
return deserializeWithObjectId(p, ctxt);
}
return deserializeFromObject(p, ctxt);
}
return _deserializeOther(p, ctxt, p.getCurrentToken());
}
protected Object vanillaDeserialize(JsonParser p, DeserializationContext ctxt, JsonToken t) throws IOException {
final Object bean = _valueInstantiator.createUsingDefault(ctxt);
// [databind#631]: Assign current value, to be accessible by custom serializers
p.setCurrentValue(bean);
if (p.hasTokenId(JsonTokenId.ID_FIELD_NAME)) {
String propName = p.getCurrentName();
do {
String relaxedName = getRelaxedName(propName);
String mappedName = properties.get(relaxedName);
defaultImplementation(p, ctxt, bean, mappedName);
} while ((propName = p.nextFieldName()) != null);
}
return bean;
}
private void defaultImplementation(JsonParser p, DeserializationContext ctxt, Object bean, String propName) throws IOException {
p.nextToken();
SettableBeanProperty prop = _beanProperties.find(propName);
if (prop != null) { // normal case
try {
prop.deserializeAndSet(p, ctxt, bean);
} catch (Exception e) {
wrapAndThrow(e, bean, propName, ctxt);
}
return;
}
handleUnknownVanilla(p, ctxt, bean, propName);
}
private String getRelaxedName(String name) {
return name.replaceAll("[_\\-]", "").toLowerCase();
}
}
Above code prints:
DeserializeIt{fieldOne='value1', fieldOneAndHalf='value15', fieldTwo='value2', fieldThree='value3', fieldFour='value4'}
See also:
Can Jackson check for duplicated properties in a case insensitive way?
From Jackson 2.9, you can provide multiple possible properties names for deserialization using the
#JsonAlias annotation. On your example, it would be like this:
class DeserializeIt {
#JsonAlias("fieldOne")
String fieldOne;
#JsonAlias("field_ONE-and_Half")
String fieldOneAndHalf;
#JsonAlias("FIELD_TWO")
String fieldTwo;
#JsonAlias("FIELD_THREE")
String fieldThree;
// and so on...
}
What worked for myself: I added an AOP component that renames all the fields of incoming object into the Camel case.

How use jackson ObjectMapper inside custom deserializer?

I try to write custom jackson deserializer. I want "look" at one field and perform auto deserialization to class, see example below:
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.ObjectCodec;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;
import com.mypackage.MyInterface;
import com.mypackage.MyFailure;
import com.mypackage.MySuccess;
import java.io.IOException;
public class MyDeserializer extends JsonDeserializer<MyInterface> {
#Override
public MyInterface deserialize(JsonParser jp, DeserializationContext ctxt)
throws IOException, JsonProcessingException {
ObjectCodec codec = jp.getCodec();
JsonNode node = codec.readTree(jp);
if (node.has("custom_field")) {
return codec.treeToValue(node, MyFailure.class);
} else {
return codec.treeToValue(node, MySuccess.class);
}
}
}
Pojos:
public class MyFailure implements MyInterface {}
public class MySuccess implements MyInterface {}
#JsonDeserialize(using = MyDeserializer.class)
public interface MyInterface {}
And I got StackOverflowError. In understand that codec.treeToValue call same deserializer. Is there a way to use codec.treeToValue or ObjectMapper.readValue(String,Class<T>) inside custome deseralizer?
The immediate problem seems to be that the #JsonDeserialize(using=...) is being picked up for your implementations of MyInterface as well as MyInterface itself: hence the endless loop.
You can fix this my overriding the setting in each implementation:
#JsonDeserialize(using=JsonDeserializer.None.class)
public static class MySuccess implements MyInterface {
}
Or by using a module instead of an annotation to configure the deserialization (and removing the annotation from MyInterface):
mapper.registerModule(new SimpleModule() {{
addDeserializer(MyInterface.class, new MyDeserializer());
}});
On a side-note, you might also consider extending StdNodeBasedDeserializer to implement deserialization based on JsonNode. For example:
#Override
public MyInterface convert(JsonNode root, DeserializationContext ctxt) throws IOException {
java.lang.reflect.Type targetType;
if (root.has("custom_field")) {
targetType = MyFailure.class;
} else {
targetType = MySuccess.class;
}
JavaType jacksonType = ctxt.getTypeFactory().constructType(targetType);
JsonDeserializer<?> deserializer = ctxt.findRootValueDeserializer(jacksonType);
JsonParser nodeParser = root.traverse(ctxt.getParser().getCodec());
nodeParser.nextToken();
return (MyInterface) deserializer.deserialize(nodeParser, ctxt);
}
There are a bunch of improvements to make to this custom deserializer, especially regarding tracking the context of the deserialization etc., but this should provide the functionality you're asking for.
In order to use your own ObjectMapper inside a custom deserializer, you can use Jackson Mix-in Annotations (the DefaultJsonDeserializer interface) to dynamically remove the custom deserializer from the POJO classes, avoiding the StackOverflowError that would otherwise be thrown as a result of objectMapper.readValue(JsonParser, Class<T>).
public class MyDeserializer extends JsonDeserializer<MyInterface> {
private static final ObjectMapper objectMapper = new ObjectMapper();
static {
objectMapper.addMixIn(MySuccess.class, DefaultJsonDeserializer.class);
objectMapper.addMixIn(MyFailure.class, DefaultJsonDeserializer.class);
}
#Override
public MyInterface deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
if (jp.getCodec().<JsonNode>readTree(jp).has("custom_field")) {
return objectMapper.readValue(jp, MyFailure.class);
} else {
return objectMapper.readValue(jp, MySuccess.class);
}
}
#JsonDeserialize
private interface DefaultJsonDeserializer {
// Reset default json deserializer
}
}
I find a solution to use object mapper inside custom deserialize
public class DummyDeserializer extends JsonDeserializer<Dummy> {
#Override
public Dummy deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
ObjectMapper om = new ObjectMapper();
om.addMixIn(NexusAccount.class, DefaultJsonDeserializer.class);
ObjectCodec oc = jsonParser.getCodec();
JsonNode node = oc.readTree(jsonParser);
String serviceType = node.path("serviceType").asText();
switch (serviceType) {
case "Dummy1":
return om.treeToValue(node, Dumm1.class);
case "Dummy2":
return om.treeToValue(node, Dummy2.class);
case "Dummy3":
return om.treeToValue(node, Dummy3.class);
default:
throw new IllegalArgumentException("Unknown Dummy type");
}
}
#JsonDeserialize
private interface DefaultJsonDeserializer {
// Reset default json deserializer
}
}
This did the trick for me:
ctxt.readValue(node, MyFailure.class)

REST Jackson JsonDeserialize, StackOverflowError after upgrade

In the previous version of jackson (1.9.2) the following code worked fine:
import org.codehaus.jackson.map.JsonDeserializer;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.map.DeserializationContext;
...
#JsonDeserialize(using = RoleDeserializer.class)
public interface RoleDto {}
public class RoleDeserializer extends SomeSharedDeserializer<RoleDto> {}
public class SomeSharedDeserializer<T> extends JsonDeserializer<T> {
#Override
public T deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException
{
return jp.readValueAs(getImplementation());
}
public Class<? extends T> getImplementation(){ ... returns some generated implementation of RoleDto }
}
After we migrated to the last jackson version (1.9.13 provided by Wildfly 8.2) we got an exception:
com.fasterxml.jackson.databind.JsonMappingException: Can not construct
instance of RoleDto, problem: abstract types either need to be mapped
to concrete types, have custom deserializer, or be instantiated with
additional type information
Ok, as in jackson new packages are used, we upgraded them to:
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.deser.std.JsonNodeDeserializer;
The deserializer is visible now (the previous exception is gone),
However, we get StackOverflowError exception. The com.fasterxml.jackson.databind.ObjectMapper reads value (line 3023):
DeserializationContext ctxt = createDeserializationContext(jp, cfg);
JsonDeserializer<Object> deser = _findRootDeserializer(ctxt, valueType);
// ok, let's get the value
if (cfg.useRootWrapping()) {
result = _unwrapAndDeserialize(jp, ctxt, cfg, valueType, deser);
} else {
result = deser.deserialize(jp, ctxt);
}
We go to the line: result = deser.deserialize(jp, ctxt);
It causes to infinite loop and StackOverflowError as a result.
One of the way which is recommended is to implement our own SomeSharedDeserializer as:
ObjectCodec oc = jp.getCodec();
JsonNode node = oc.readTree(jp);
//here manually create new object and return it
But our classes are generated. As another solution I tried to use
ObjectMapper mapper = new ObjectMapper();
mapper.readValue(jp, getImplementation());
But got the same result - StackOverflow exception.
How can we fix it? Can we use some deserializer, to pass it JsonParser instance, generated class that implements base interface and without StackOverflowError?
Here is you can find a full description and trials to find a solution.
The following solution has been found:
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.BeanDescription;
import com.fasterxml.jackson.databind.DeserializationConfig;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.cfg.DeserializerFactoryConfig;
import com.fasterxml.jackson.databind.deser.BeanDeserializerFactory;
import com.fasterxml.jackson.databind.deser.ResolvableDeserializer;
import com.fasterxml.jackson.databind.type.SimpleType;
...
public abstract class RestDtoDeserializer<T> extends JsonDeserializer<T>
{
#Override
public T deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException
{
DeserializationConfig config = ctxt.getConfig();
SimpleType simpleType = SimpleType.construct(getImplementationClass());
BeanDescription beanDesc = config.introspect(simpleType);
BeanDeserializerFactory instance = new BeanDeserializerFactory(new DeserializerFactoryConfig());
JsonDeserializer deserializer = instance.buildBeanDeserializer(ctxt, simpleType, beanDesc);
((ResolvableDeserializer)deserializer).resolve(ctxt);
return (T) deserializer.deserialize(jp, ctxt);
}
public abstract Class<? extends T> getImplementationClass();

Categories

Resources