微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

反序列化抽象父类型的构造函数参数时获取 UnresolvedForwardReference

如何解决反序列化抽象父类型的构造函数参数时获取 UnresolvedForwardReference

package com.utils;

import com.fasterxml.jackson.annotation.*;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;

import javax.xml.bind.annotation.*;

public class Test {
    
    public static void main(String[] args) throws Exception {
        XmlMapper xmlMapper = new XmlMapper();
        String dogString = "<Dog _class=\"com.utils.Dog\" id=\"Dog123\">\n" +
                "\t<name>Spot</name>\n" +
                "</Dog>";

        Dog dog = xmlMapper.readValue(dogString,Dog.class);
        System.out.println(dog);

        String ownerString ="<Owner _class=\"com.utils.Owner\" id=\"Owner123\">\n" +
                "\t<animal>Dog123</animal>\n" +
                "</Owner>";
        Owner owner = xmlMapper.readValue(ownerString,Owner.class);
        System.out.println(owner);
    }
}

@JsonIdentityInfo(
        generator = ObjectIdGenerators.PropertyGenerator.class,property = "id")
@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS,include = JsonTypeInfo.As.PROPERTY)
@XmlAccessorType(XmlAccesstype.FIELD)
@JsonSubTypes({
        @JsonSubTypes.Type(value = Dog.class),@JsonSubTypes.Type(value = Owner.class),})
abstract class MyObject {

    @XmlAttribute
    @XmlID
    String id = getClass().getSimpleName() + "123";

    @JsonProperty("id")
    public String getId() {
        return id;
    }
}

abstract class Animal extends MyObject {

    @JsonProperty("name")
    String name;

    public Animal(String name) {
        this.name = name;
    }
}

@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class,resolver = SimpleObjectIdResolver.class,property = "id",scope = Dog.class)
class Dog extends Animal {

    @JsonCreator
    public Dog(@JsonProperty("name") String name) {
        super(name);
    }
}

@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class,scope = Owner.class)
class Owner extends MyObject {

    @XmlIDREF
    Animal animal;

    @JsonCreator
    public Owner(@JsonProperty("animal") Animal animal) {
        this.animal = animal;
    }

    public Animal getAnimal() {
        return animal;
    }
}

大家好,

我得到的堆栈跟踪如下:

Exception in thread "main" com.fasterxml.jackson.databind.deser.UnresolvedForwardReference: Could not resolve Object Id [Dog123] -- unresolved forward-reference?
 at [Source: (StringReader); line: 2,column: 25] (through reference chain: com.utils.Owner["animal"])
    at com.fasterxml.jackson.databind.deser.AbstractDeserializer._deserializefromObjectId(AbstractDeserializer.java:334)
    at com.fasterxml.jackson.databind.deser.AbstractDeserializer.deserializeWithType(AbstractDeserializer.java:246)
...

这是构造函数不接受抽象类型的问题吗?

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。