简体   繁体   中英

Can jackson deserialize from different JSON string to same object?

I have a JSON string, like this:

{
...
"token": "abc123"
...
}

Then for some reason, have to update to a new structure, the expected incoming JSON string becomes:

{
...
"token": {"property01":"true", "property02":"false", "value": "abc123"}
...
}

Originally, the token field was in string type, now, it becomes an object, with additional properties.

I need to handle both format for backward compatibility, can jackson handle this case?

You could do this by creating your own deserializer:

class FooJsonDeserializer extends JsonDeserializer<Foo> {

    @Override
    public Foo deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
        Foo foo = new Foo();
        //deserialize your data here
        return foo;
    }
}

And don't forget to add the deserializer to your class

@JsonDeserialize(using = FooJsonDeserializer.class)
class Foo {
    ...
}

您可以使用@JsonDeserialize(using=YourCustomDeserializer.class)注释token设置程序,并仅为一个字段反序列化提供逻辑。

You could use the Jackson module I wrote for handling versioning. See the examples on the README for info on how to use it.

https://github.com/jonpeterson/jackson-module-model-versioning

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM