【问题标题】:How do I deserialize circular references (serialized by Newtonsoft.Json) with Jackson?如何使用 Jackson 反序列化循环引用(由 Newtonsoft.Json 序列化)?
【发布时间】:2017-03-20 10:25:37
【问题描述】:

我必须使用循环引用反序列化 JSON。 第一次出现的对象有:

"$id":"1"

参考如下:

{"$ref":"1"}

使用@JsonIdentityInfo 我可以使 $id 可读,但杰克逊不会阅读参考资料。 如果我手动删除“$ref”的东西,反序列化就会起作用,并且 JSON 字符串中只有引用键本身。

如何让 Jackson 以 "$ref" 样式处理引用?

【问题讨论】:

    标签: java json jackson deserialization circular-reference


    【解决方案1】:

    我尝试了自己的反序列化器,但对于这个非常简单的问题来说,它似乎要复杂得多。

    我要反序列化的类得到:

    @JsonIdentityInfo(generator=ObjectIdGenerators.IntSequenceGenerator.class, property="$id")
    

    我获取整个 JSON 字符串并用正则表达式替换 ref 内容。

    String regex = "\\{\\\"\\$ref\\\":\\\"(\\d{1,})*\\\"\\}";
    Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE | Pattern.DOTALL);
    
    Matcher matcher = pattern.matcher(jsonString);
    String resultString="";
    if (matcher.find())
    {
        resultString = matcher.replaceAll("$1");
    }
    

    更换字符串几乎不需要时间。

    【讨论】:

      猜你喜欢
      • 2015-05-20
      • 2019-07-28
      • 1970-01-01
      • 2014-12-13
      • 2012-11-18
      • 2021-12-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多