【问题标题】:Unmarshalling to a subclass with JAXB使用 JAXB 解组到子类
【发布时间】:2011-07-03 06:21:47
【问题描述】:

我有一个类似这样的 JSON:

objects:[{
   id:"p452365",
   type:"photo",
   link:"http://xxx.zz"
},
{
   id:"v7833",
   type:"video",
   link:"http://xxx.yy",
   length:"4.12"
}
]

在超类 Entity 中,有 2 个实例变量:id 和 type。在我的扩展 XmlAdapter 类中,我尝试将我的 Entity 实例转换为 ex 的子类型。 Photo

public HashMap<String, List<Column>> unmarshal(Feeds f) throws Exception {
        for(Feed feed : f.getFeeds()){
            System.out.println("Entity id for feed : " + feed.getId());
            for(Entity e:feed.getObjects()){
                if (e instanceof Photo){
                    // Of course it's not
                }
            }
        }
        return (HashMap<String, List<Column>>)fm.map(f.getFeeds());
    }

当然 e 不是 Photo 的实例,我在那里拍了一张。:) 我想做的是在某个时候干扰 JAXB 进程并根据 JSON 中的类型值解组。我想知道在哪里以及如何。

【问题讨论】:

    标签: jaxb


    【解决方案1】:

    我之前对类似问题的回答可能对这里有所帮助。本质上,它在 EclipseLink JAXB (MOXy) 中使用 @XmlDescrimatorNode。请注意,我是 MOXy 技术负责人。

    您也可以使用 XmlAdapter 来执行此操作。 AdaptedEntity 将具有 Entity 及其子类的所有属性。

    【讨论】:

    • 在更改 JAXB impl 之前,我真的很想尝试第二个选项。感谢您的回答。
    • 我改变了主意。现在我正在使用 MOXy。我将 jaxb.properties 文件放入我的域类所在的包中。但我得到了这个异常:java.lang.ClassNotFoundException: org.eclipse.persistence.jaxb.JAXBContextFactory.你有什么想法吗?顺便说一句,我目前正在使用 RestEasy。
    猜你喜欢
    • 1970-01-01
    • 2010-10-11
    • 2016-01-26
    • 1970-01-01
    • 2010-12-28
    • 1970-01-01
    • 2023-03-14
    • 1970-01-01
    相关资源
    最近更新 更多