开发者

Jackson deserialization Unexpected token (END_OBJECT),

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 'ty开发者_C百科pe.code' that is to contain type id  (for class Animal)

Any idea what's wrong. Thank you.


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜