gpt4 book ai didi

java - 将继承与 JAXB 结合使用

转载 作者:行者123 更新时间:2023-11-30 06:22:07 25 4
gpt4 key购买 nike

我有 xml:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<UserTypes>
<UserType Id="1">
<Members>
<Member UserTypeId="4" Name="Name1" />
<Member UserTypeId="1" Name="Name2" />
</Members>
</UserType>
<UserType Id="23" ItemUserTypeId="232">
<Description />
</UserType>
</UserTypes>

某些元素具有特定的嵌套元素和属性。在 Java 中,我创建了通用类及其继承者:

@XmlAccessorType(XmlAccessType.FIELD)
public class UserType {

@XmlAttribute(name = "Id", required = true)
private Integer id;

private UserTypeKind userTypeKindType;
//getters and setters
}

@XmlAccessorType(XmlAccessType.FIELD)
public class StructUserType extends UserType {

@XmlElement(name = "Members")
MembersList membersList = new MembersList();

static class MembersList {
@XmlElement(name = "Member")
List<Member> members = new ArrayList<>();
}

static class Member {
@XmlAttribute(name = "Name", required = true)
String name;

@XmlAttribute(name = "UserTypeId", required = true)
long userTypeId;
}
}

@XmlAccessorType(XmlAccessType.FIELD)
public class ListUserType extends UserType {

@XmlAttribute(name = "ItemUserTypeId", required = true)
private long itemUserTypeId;

public long getItemUserTypeId() {
return itemUserTypeId;
}

public void setItemUserTypeId(long itemUserTypeId) {
this.itemUserTypeId = itemUserTypeId;
}
}

我想将我的对象编码为 xml。我愿意:

List<UserType> userTypes = new ArrayList<>();

StructUserType structUserType = new StructUserType();
smbpStructUserType.setId(1);
SmbpStructUserType.Member member1 = new SmbpStructUserType.Member();
member1.name = "Name1";
member1.userTypeId = 4;
SmbpStructUserType.Member member2 = new SmbpStructUserType.Member();
member2.name = "Name2";
member2.userTypeId = 1;
structUserType.membersList.members.add(member1);
structUserType.membersList.members.add(member2);


ListUserType listUserType = new ListUserType();
listUserType.setId(23);
smbpListUserType.setItemUserTypeId(232);

userTypes.add(structUserType);

但是当我尝试进行编码(marshal)时,只有落入最终 xml 的元素仅在主类 (UserType) 中定义,所有元素都是从主类继承的。这有什么问题吗?需要什么样的 JAXB 配置才能使子类的元素也落入最终的 xml 中?

最佳答案

我认为有几个选择。最简单的就是给你的UserType标记两个不同的名称,例如 StructUserTypeListUserType 。然后你需要在根元素中指定哪个名称适合哪个类

@XmlElements({
@XmlElement(name = "StructUserType", type = StructUserType.class),
@XmlElement(name = "ListUserType", type = ListUserType.class)
})
private List<UserType> userTypse;

另一个选项是使用@XmlJavaTypeAdapter(YourAddapter.class) ,在 YourAddapter 类中扩展 XmlAdapter 类并覆盖 marshal方法,您可以在其中指定如何整理您的 UserType 标记。

关于java - 将继承与 JAXB 结合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47902797/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com