gpt4 book ai didi

java - 包含映射或简单类型的 JAXB 对象

转载 作者:太空宇宙 更新时间:2023-11-04 08:05:08 25 4
gpt4 key购买 nike

包含 map 或简单类型的 JAXB 对象

这个想法是有一个类,它有一个成员“值”,它可以包含简单类型,如字符串或整数,以及简单类型的映射,连接到 boolean 值(例如,HashMap

这是一个“工作”示例,它显示了我想要做的事情:

package test;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import javax.xml.bind.JAXB;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElements;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlSeeAlso;

@XmlRootElement
public class TestJAXB {
public static void main(String[] args) {
TestJAXB test = new TestJAXB();
JAXB.marshal(test, new File("foo.xml"));
}

Container one;
Container two;
Container three;
Container four;

public TestJAXB() {
this.one = new Container("foo");
this.two = new Container("42");
this.three = new Container(true);

HashMap<Object, Boolean> map = new HashMap<Object, Boolean>();
map.put("foo", false);
map.put("bar", false);
map.put("foobar", true);

this.four = new Container(map);

}

@XmlElement
public Container getOne() {
return one;
}

public void setOne(Container one) {
this.one = one;
}

@XmlElement
public Container getTwo() {
return two;
}

public void setTwo(Container two) {
this.two = two;
}

@XmlElement
public Container getThree() {
return three;
}

public void setThree(Container three) {
this.three = three;
}

@XmlElement
public Container getFour() {
return four;
}

public void setFour(Container four) {
this.four = four;
}
}

@XmlRootElement
@XmlSeeAlso(HashMap.class)
class Container {
Map<Object, Boolean> value = null;
boolean wasMap = false;

protected Container() {

}

protected Container(Object value) {
this.setValue(value);
}

@XmlElements({ @XmlElement(name = "string", type = String.class), @XmlElement(name = "bool", type = Boolean.class), @XmlElement(name = "int", type = Integer.class), })
public Object getValue() {
if (wasMap) {
return value;
} else {
return value.keySet().toArray()[0];
}
}

@SuppressWarnings("unchecked")
public void setValue(Object value) {
if (value instanceof Map) {
this.value = (Map<Object, Boolean>) value;
this.wasMap = true;
} else {
this.value = new HashMap<Object, Boolean>();
this.value.put(value, false);
this.wasMap = false;
}
}
}

嗯,简单的类型被编码为精细的 xml,但映射的元素保持为空:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<testJAXB>
<four>
<string xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="hashMap"/>
</four>
<one>
<string>foo</string>
</one>
<three>
<bool>true</bool>
</three>
<two>
<string>42</string>
</two>
</testJAXB>

我做错了什么?我能做什么?

最佳答案

您必须为 HashMap 创建javax.xml.bind.annotation.adapters.XmlAdapter
您可以在此处获取示例
Example

关于java - 包含映射或简单类型的 JAXB 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12196517/

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