杰克逊预处理反序列化 [英] Jackson preprocess deserialization

查看:70
本文介绍了杰克逊预处理反序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我反序列化一个对象时,我想对json进行一些转换(移动/更改/添加字段),然后继续处理反序列化的对象.这可能吗?

When I deserialize an object, I want to do some transformation on the json (move/change/add fields) then continue processing the deserialized object. Is this possible?

简单示例:

输入JSON

{
    "first": "thing",
    "seconds": [ 55, 67, 12 ]
}

我的对象

public class MyObject {
    private String new;
    private int second;

    // getters and setters
}

反序列化器

public class MyObjectDeserializer extends JsonDeserializer<MyObject> {

    @Override
    public MyObject deserialize(final JsonParser p, final DeserializationContext ctxt) throws IOException {
        JsonNode json = p.getCodec().readTree(p);
        JsonNode translatedJson = translate(json);

        // continue processing MyObject like ObjectMapper#readValue would using the translated json
    }

    private JsonNode translate(final JsonNode json) {
        ObjectNode object = (ObjectNode) json;

        // Update 'first' to 'new'
        object.put("new", object.get("first").asText()).remove("first");

        // Find the max in 'seconds' and add it as 'second'
        JsonNode seconds = object.get("seconds");
        int max = 0;
        for (int i = 0; i < seconds.size(); i++) {
            max = Math.max(max, seconds.get(i).asInt());
        }
        object.put("second", max).remove("seconds");

        return object;
    }
}

推荐答案

是的,您可以使用JsonParser中的ObjectCodec进行此操作:

Yes, you can do this using the ObjectCodec from the JsonParser:

public class MyObjectDeserializer extends JsonDeserializer<MyObject> {

    @Override
    public MyObject deserialize(final JsonParser p, final DeserializationContext ctxt) throws IOException {
        ObjectCodec codec = p.getCodec();
        JsonNode json = coded.readTree(p);
        JsonNode translatedJson = translate(json);

        // continue processing MyObject like ObjectMapper#readValue would using the translated json
        return codec.treeToValue(node, MyObject.class);
    }

    private JsonNode translate(final JsonNode json) {
        ObjectNode object = (ObjectNode) json;

        // Update 'first' to 'new'
        object.put("new", object.get("first").asText()).remove("first");

        // Find the max in 'seconds' and add it as 'second'
        JsonNode seconds = object.get("seconds");
        int max = 0;
        for (int i = 0; i < seconds.size(); i++) {
            max = Math.max(max, seconds.get(i).asInt());
        }
        object.put("second", max).remove("seconds");

        return object;
    }
}

请注意,您将无法在Java类中使用new作为字段名称,因为它是保留关键字.

Note that you won't be able to use new as field name in the Java class because it is a reserved keyword.

这篇关于杰克逊预处理反序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆