【问题标题】:XML unmarshalling using JAXB, with field type based on XML attribute value?使用 JAXB 进行 XML 解组,字段类型基于 XML 属性值?
【发布时间】:2018-06-27 13:19:25
【问题描述】:

我的应用程序从另一个应用程序接收以下形式的 xml:

<targetedMessage>
    <sender>the sender</sender>
    <payload class="other.app.classpath.Foo">
        <id>1</id>
    </payload>
</targetedMessage>

其中Foo 是我的模块和其他应用程序中存在的几个类中的任何一个,并实现了一个通用接口:

@XmlAccessorType(value = XmlAccessType.FIELD)
@XmlRootElement
public class Foo implements MyInterface {
    private long id;
    \\ getters and setters
}

TargetedMessage 类是:

@XmlAccessorType(value = XmlAccessType.FIELD)
@XmlRootElement
public class TargetedMessage {
    private String sender;
    private MyInterface payload;
    \\ getters and setters
}

我有一个枚举,它将其他应用程序的类路径映射到我的模块中的类:

public enum MyClasses {
    FOO(Foo.class, "other.app.classpath.Foo"),
    BAR(Bar.class, "other.app.classpath.Bar"),
    \\ ...
}

使用 JAXB,是否可以解组 xml 以使有效负载具有正确的类型(在上述情况下,有效负载类将为 Foo)。

【问题讨论】:

标签: java xml jaxb unmarshalling xml-attribute


【解决方案1】:

我不了解 JAXB,但 SimpleXml 可以做到:

@XmlName("targetedMessage")
public class TargetedMessage {
    String sender;
    @XmlAbstactClass(attribute="class", types={
        @TypeMap(name="other.app.classpath.Foo", type=Foo.class),
        @TypeMap(name="other.app.classpath.Bar", type=Bar.class)
    })
    Payload payload;
}
interface Payload {}
public class Foo implements Payload {
    Integer id;
}
public class Bar implements Payload {
    String name;
}

final String data = ...

final SimpleXml simple = new SimpleXml();
final TargetedMessage message = simple.fromXml(data, TargetedMessage.class);
System.out.println(message.payload.getClass().getSimpleName());
System.out.println(((Foo)message.payload).id);

将输出:

Foo
1

来自 Maven 中心:

<dependency>
    <groupId>com.github.codemonstur</groupId>
    <artifactId>simplexml</artifactId>
    <version>1.5.0</version>
</dependency>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-02-14
    • 1970-01-01
    • 2014-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-17
    相关资源
    最近更新 更多