Jackson deserialization Unexpected token (END_OBJECT),

為{幸葍}努か 提交于 2020-01-02 06:49:21

问题


I am trying to deserialize a JSON Object into a Java Object using Jackson annotation on one Abstact class "Animal":

@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 a sample JSON string:

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

The problem is that the property "type" 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 "property" value but nothing. the Exeption is this

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's wrong. Thank you.


回答1:


Throwing this out there after having found no solution to this problem. I came up with my own style if it interests anyone who stumbles upon this. Feel free to add your own solutions if you find another way.

I have implemented in my enums to fix this problem has been to add a findByType method that allows you to search on a string representation of the enum key value. So in your example you have an enum 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 would have a public method findByTypeCode that would return the type for the key you search on:

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;
}

I hope this helps. Like I said, there may be a solution out there that tackles this directly, but I haven't found one and don't need to waste more time searching for a solution when this works well enough.




回答2:


I'm beginner with jackson but I think you must search tree parsing like explained here



来源:https://stackoverflow.com/questions/7502972/jackson-deserialization-unexpected-token-end-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!