When I try to return Map<String, List<Map<String, String>>> from the RestController, I get the following error:
"message": "Could not write JSON: Class java.util.ArrayList not subtype of [map type; class java.util.Map, [simple type, class java.lang.String] -> [simple type, class java.lang.Object]]; nested exception is com.fasterxml.jackson.databind.JsonMappingException: Class java.util.ArrayList not subtype of [map type; class java.util.Map, [simple type, class java.lang.String] -> [simple type, class java.lang.Object]]
Can some help me with the solution?
Related
MyClass.java:
class MyClass<T extends Serializable> implements Serializable{
#JsonProperty(value = "allowedValues", required = false)
private List<T> allowedValues;
}
I'm getting this exception while deserializing this above object persisted in the DB.
How do i resolve this?
Error while de-serializing json to MyClass.java: com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of java.io.Serializable (no Creators, like default construct, exist): abstract types either need to be mapped to concrete types, have custom deserializer, or contain additional type information at [Source: (String)"{"allowedValues":["a","b","c"]} (through reference chain: com.babu.model.MyClass->["allowedValues"]->java.util.ArrayList[0])
I'm using JSON Jackson on SpringBoot context.
I have a problem with Jackson deserialization with Generic type constraint.
This code work fine :
public abstract class AbstractSyncableWriteAndReadResource<T, K> extends AbstractSyncableReadResource<T, K> {
...
#Timed
#RequestMapping(method = RequestMethod.PUT, produces = MediaType.APPLICATION_JSON_VALUE)
#Transactional
public ResponseEntity<List<SynQueuDTO<T>>> syncPushPut(#RequestBody List<SynQueuDTO<T>> entities) {
...
}
}
But this code don't work :
This code work fine :
public abstract class AbstractSyncableWriteAndReadResource<T extends EntitySyncableWrite, K> extends AbstractSyncableReadResource<T, K> {
...
#Timed
#RequestMapping(method = RequestMethod.PUT, produces = MediaType.APPLICATION_JSON_VALUE)
#Transactional
public ResponseEntity<List<SynQueuDTO<T>>> syncPushPut(#RequestBody List<SynQueuDTO<T>> entities) {
...
}
}
There is only one difference : add Java interface on Generic for constraint Class's type.
Exception :
Type definition error: [simple type, class xxx.xxx.xxx.EntitySyncableWrite]; nested exception is com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of `xxx.xxx.xxx.EntitySyncableWrite` (no Creators, like default construct, exist): abstract types either need to be mapped to concrete types, have custom deserializer, or contain additional type information\n at [Source: (PushbackInputStream); line: 5, column: 26]
I try a lot of configurations to force Jackson take Class instead of Interface informations but without success :
#JsonTypeInfo(use= JsonTypeInfo.Id.NAME, include= JsonTypeInfo.As.WRAPPER_OBJECT)
or #JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type") (ko)
Do you have some idea?
Thanks
[UPDATE]
An another use case that work very well :
public abstract class AbstractSyncableWriteAndReadResource<T extends EntitySyncableWrite, K> ... {
public ResponseEntity<List<SyncQueuDTO<T>>> syncPushPut( #RequestBody SyncQueuDTO<T> data) {
...
}
}
But don't work when add RequestBody as List :
public abstract class AbstractSyncableWriteAndReadResource<T extends EntitySyncableWrite, K> ... {
public ResponseEntity<List<SyncQueuDTO<T>>> syncPushPut( #RequestBody List<SyncQueuDTO<T>> data) {
...
}
}
Exception :
Type definition error: [simple type, class xx.xx.xx.EntitySyncableWrite]; nested exception is com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of `xx.xx.xx.EntitySyncableWrite` (no Creators, like default construct, exist): abstract types either need to be mapped to concrete types, have custom deserializer, or contain additional type information\n at [Source: (PushbackInputStream); line: 5, column: 26] (through reference chain: java.util.ArrayList[0]->xx.xx.xx.SyncQueuDTO[\"serverVersion\"])
With Map JSON array of objects to #RequestBody List<T> using jackson inspiration I solved this Jackson/JVM limitation as :
public abstract class AbstractSyncableWriteAndReadResource<T extends EntitySyncableWrite, K> extends AbstractSyncableReadResource<T, K> {
...
public ResponseEntity<List<SyncQueuDTO<T>>> syncPushPut(#RequestBody SyncQueuDTOList<T> queuList) {
....
}
}
and ArrayList implementation :
public class SyncQueuDTOList<T extends EntitySyncableWrite> extends ArrayList<SyncQueuDTO<T>> {}
I am using Jackson to read a user-provided JSON file, mapping it on an object. In case of error in the JSON structure, I get a JsonMappingException that is not readable by the user. For example:
my.package.shadow.jackson.databind.JsonMappingException: Class java.util.ArrayList not subtype of [map type; class java.util.Map, [simple type, class java.lang.String] -> [collection type; class java.util.List, contains [simple type, class java.lang.String]]] (through reference chain: my.package.configuration.Configuration["conf"]->java.util.HashMap["foo"])
at my.package.shadow.jackson.databind.JsonMappingException.wrapWithPath(JsonMappingException.java:391)
...
Caused by: java.lang.IllegalArgumentException: Class java.util.ArrayList not subtype of [map type; class java.util.Map, [simple type, class java.lang.String] -> [collection type; class java.util.List, contains [simple type, class java.lang.String]]]
at my.package.shadow.jackson.databind.type.TypeFactory.constructSpecializedType(TypeFactory.java:357)
...
Is there a way to get a more readable error message, or the line and column in the JSON source that corresponds to the exception?
To clarify, the user writes this
{
"conf": {
"foo": ["bar"]
}
}
but I expect
{
"conf": {
"foo": {
"bar" : ["a", "b", "c"]
}
}
}
A snippet of the code:
public class ReadConfiguration {
public static Configuration readConfiguration(File file) {
ObjectMapper mapper = new ObjectMapper(new JsonFactory());
Configuration conf = mapper.readValue(file, Configuration.class);
return conf
}
}
Here I am Using LocalDate class of java 1.8.In my bean I took return type as LocalDate. And I am sending date formate as 07/01/2017. when I am trying to save that I am getting follwing exception.
org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver] (default task-33) Failed to read HTTP message: org.springframework.http.converter.HttpMessageNotReadableException: Could not read document: Can not instantiate value of type [simple type, class java.time.LocalDate] from String value ('07/01/2017'); no single-String constructor/factory method
at [Source: java.io.PushbackInputStream#39959f38; line: 1, column: 650] (through reference chain: com.pro.bean.ParentBean["Soici"]->com.pro.bean.Soici["fecha_de_solicitud"]); nested exception is com.fasterxml.jackson.databind.JsonMappingException: Can not instantiate value of type [simple type, class java.time.LocalDate] from String value ('07/01/2017'); no single-String constructor/factory method
at [Source: java.io.PushbackInputStream#39959f38; line: 1, column: 650] (through reference chain: com.pro.bean.ParentBean["Soici"]->com.pro.bean.Soici["fecha_de_solici"])
Add com.fasterxml.jackson.datatype-jsr310 dependency
Then configure Jackson2ObjectMapper with
#Bean(name = "OBJECT_MAPPER_BEAN")
public ObjectMapper jsonObjectMapper() {
return Jackson2ObjectMapperBuilder.json()
.serializationInclusion(JsonInclude.Include.NON_NULL) // Don’t include null values
.featuresToDisable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS) //ISODate
.modules(new JSR310Module())
.build();
}
SOURCE: https://blog.oio.de/2015/06/13/add-support-for-java-8-date-time-api-to-jackson-serialized-rest-web-services/
I'm currently trying to serialize and deserialize a custom Map type as JSON using Jackson 2.8.4. I've managed to get serialization working based on this answer, but I'm struggling with deserialization. Here is an example:
public class TestMapSerialize {
public interface TestMapGetters {
Map<String, String> getFooMap();
Map<String, String> getBarMap();
}
#JsonSerialize(as = TestMapGetters.class)
public static class TestMap extends ForwardingMap<String, String>
implements TestMapGetters {
private Map<String, String> fooMap;
private Map<String, String> barMap;
#Override
protected Map<String, String> delegate() {
return ImmutableMap.<String, String>builder()
.putAll(fooMap)
.putAll(barMap)
.build();
}
// Getters and setters...
}
public static void main(String[] args) throws IOException {
final ObjectMapper mapper = new ObjectMapper();
final TestMap map = new TestMap();
map.setFooMap(ImmutableMap.of("a", "b", "c", "d"));
map.setBarMap(ImmutableMap.of("e", "f", "g", "h"));
final String json = mapper.writeValueAsString(map);
// Prints {"fooMap":{"a":"b","c":"d"},"barMap":{"e":"f","g":"h"}} as expected.
System.out.println(json);
// Throws JsonMappingException, see below.
final TestMap copy = mapper.readValue(json, TestMap.class);
}
}
When I try to deserialize as above, I get an exception:
Exception in thread "main" com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.lang.String out of START_OBJECT token
at [Source: {"fooMap":{"a":"b","c":"d"},"barMap":{"e":"f","g":"h"}}; line: 1, column: 11] (through reference chain: test.TestMapSerialize$TestMap["fooMap"])
at com.fasterxml.jackson.databind.JsonMappingException.from(JsonMappingException.java:270)
at com.fasterxml.jackson.databind.DeserializationContext.reportMappingException(DeserializationContext.java:1234)
at com.fasterxml.jackson.databind.DeserializationContext.handleUnexpectedToken(DeserializationContext.java:1122)
at com.fasterxml.jackson.databind.DeserializationContext.handleUnexpectedToken(DeserializationContext.java:1075)
at com.fasterxml.jackson.databind.deser.std.StringDeserializer.deserialize(StringDeserializer.java:60)
at com.fasterxml.jackson.databind.deser.std.StringDeserializer.deserialize(StringDeserializer.java:11)
at com.fasterxml.jackson.databind.deser.std.MapDeserializer._readAndBindStringKeyMap(MapDeserializer.java:517)
at com.fasterxml.jackson.databind.deser.std.MapDeserializer.deserialize(MapDeserializer.java:362)
at com.fasterxml.jackson.databind.deser.std.MapDeserializer.deserialize(MapDeserializer.java:27)
at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:3798)
at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2842)
at test.TestMapSerialize.main(TestMapSerialize.java:66)
So Jackson is still trying to deseralize my class as though it's a generic Map, which won't work because it's a bean. I've tried adding #JsonDeserialize(as = TestMapGetters.class) as well, but then I get:
Exception in thread "main" com.fasterxml.jackson.databind.JsonMappingException: Failed to narrow type [map type; class test.TestMapSerialize$TestMap, [simple type, class java.lang.String] -> [simple type, class java.lang.String]] with annotation (value test.TestMapSerialize$TestMapGetters), from 'test.TestMapSerialize$TestMap': Class test.TestMapSerialize$TestMapGetters not subtype of [map type; class test.TestMapSerialize$TestMap, [simple type, class java.lang.String] -> [simple type, class java.lang.String]]
at com.fasterxml.jackson.databind.AnnotationIntrospector.refineDeserializationType(AnnotationIntrospector.java:1194)
at com.fasterxml.jackson.databind.deser.DeserializerCache.modifyTypeByAnnotation(DeserializerCache.java:519)
at com.fasterxml.jackson.databind.deser.DeserializerCache._createDeserializer(DeserializerCache.java:333)
at com.fasterxml.jackson.databind.deser.DeserializerCache._createAndCache2(DeserializerCache.java:264)
at com.fasterxml.jackson.databind.deser.DeserializerCache._createAndCacheValueDeserializer(DeserializerCache.java:244)
at com.fasterxml.jackson.databind.deser.DeserializerCache.findValueDeserializer(DeserializerCache.java:142)
at com.fasterxml.jackson.databind.DeserializationContext.findRootValueDeserializer(DeserializationContext.java:476)
at com.fasterxml.jackson.databind.ObjectMapper._findRootDeserializer(ObjectMapper.java:3899)
at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:3794)
at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2842)
at test.TestMapSerialize.main(TestMapSerialize.java:68)
Caused by: java.lang.IllegalArgumentException: Class test.TestMapSerialize$TestMapGetters not subtype of [map type; class test.TestMapSerialize$TestMap, [simple type, class java.lang.String] -> [simple type, class java.lang.String]]
at com.fasterxml.jackson.databind.type.TypeFactory.constructSpecializedType(TypeFactory.java:359)
at com.fasterxml.jackson.databind.AnnotationIntrospector.refineDeserializationType(AnnotationIntrospector.java:1192)
... 10 more
which makes sense, because it's not a subtype. I'd rather not have to write a custom deserializer, since this would deserialize fine if my object weren't a subtype of Map. Is there any way I can tell Jackson to ignore the fact that my class is a Map and just deserialize as a bean?
I figured out that I can add a static creator method to my TestMap class:
#JsonCreator
static TestMap fromJson(
#JsonProperty("fooMap") ImmutableMap<String, String> fooMap,
#JsonProperty("barMap") ImmutableMap<String, String> barMap) {
final TestMap map = new TestMap();
map.setFooMap(fooMap);
map.setBarMap(barMap);
return map;
}
It would still be nice to have a way to say "just serialize and deserialize as a POJO" to avoid the whole #JsonCreator and #JsonSerialize(as) rigamarole.