Jackson Deserialization Unexpected Token (END_OBJECT),

I am trying to deserialize a JSON object into a Java object using Jackson's annotation in one Abstact "Animal" class:

@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type") @JsonSubTypes({@Type(value = Dog.class, name = "chien"), @Type(value = Cat.class, name= "chat")}) 

and here is an example JSON string:

 { "name": "Chihuahua", "type": { "code": "chien", "description": "Chien mechant" } } 

The problem is that the "type" property in the JSON object is also an object. when I try to deserialize, I have this exception:

 Caused by: org.codehaus.jackson.map.JsonMappingException: Could not resolve type id '{' into a subtype of [simple type, class Animal] 

I tried to use "type.code" as a "property", but nothing. Exeption is

 Caused by: org.codehaus.jackson.map.JsonMappingException: Unexpected token (END_OBJECT), expected FIELD_NAME: missing property 'type.code' that is to contain type id (for class Animal) 

Any idea what is wrong. Thanks.

+4
source share
2 answers

Throwing it there, not finding a solution to this problem. I came up with my own style if it interests anyone who stumbles upon it. Feel free to add your own solutions if you find another way.

I applied a fix for this problem in my enumerations to add the findByType method, which allows you to search for a string representation of the enumeration key value. So, in your example, you have an enumeration with a key / value pair as such,

 pubilc enum MyEnum { ... CHIEN("chien", "Chien mechant") ... } // Map used to hold mappings between the event key and description private static final Map<String, String> MY_MAP = new HashMap<String, String>(); // Statically fills the #MY_MAP. static { for (final MyEnum myEnum: MyEnum.values()) { MY_MAP.put(myEnum.getKey(), myEnum); } } 

and then you will have a public findByTypeCode method that will return the type for the key you are looking for:

 public static MyEnum findByKey(String pKey) { final MyEnum match = MY_MAP.get(pKey); if (match == null) { throw new SomeNotFoundException("No match found for the given key: " + pKey); } return match; } 

Hope this helps. As I said, there may be a solution that will solve it directly, but I did not find it and should not spend more time looking for a solution when it works well enough.

0
source

I start with jackson, but I think you should look for tree parsing as described here

-3
source

Source: https://habr.com/ru/post/974855/


All Articles