1

假设我有以下json:

{
    "first_path": "/just/a/path",
    "second_path": "/just/another/path",
    "relative_path": { "$relative": "some_file" },
}

我有我无法修改的课程:

public class Paths {
    public String first_path;
    public String second_path;
    public String third_path; // Can't mark this with annotations
}

我想要的是对所有字符串值应用一些自定义反序列化逻辑,如果它们在 json 中看起来像 { "$...": "..." }。在我的示例中,我显然要根据一些逻辑将相对路径转换为绝对路径,并将绝对路径放入 Paths.third_path 成员。

我如何与杰克逊一起实现这一目标?

4

1 回答 1

0

花了几个小时后,我找到了通过以下方式覆盖字符串反序列化的方法:

public class PathJsonDeserializer extends JsonDeserializer<String> {
    @Override
    public String deserialize(JsonParser parser, DeserializationContext context) 
                  throws IOException, JsonProcessingException {

        JsonToken token = parser.getCurrentToken();
        if (token.equals(JsonToken.START_OBJECT)) {
            // This String value looks like an object - try to parse $relative
            Path path = parser.readValueAs(Path.class);
            return path.$relative;
        } else {
            // This is normal String value
            return parser.getText();
        }
    }
}

路径类是:

public class Path {
    public String $relative;
}

PathJsonDeserializer 应该像往常一样通过模块添加到映射器。还有其他更多的组件方法吗?对于这种情况,如果我有很少的基于 $ 的规则具有不同的逻辑。

于 2013-07-02T20:36:27.920 回答