基本上你需要一个 XML 适配器。你可以在 KeyValue 类的名称上调整,以获得所需的特定输出。
Parameter.java
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import java.util.Map;
@XmlRootElement(name = "data")
@XmlAccessorType(XmlAccessType.FIELD)
public class Parameters {
@XmlJavaTypeAdapter(value = Adapter.class)
private Map<String, String> parametersMap;
}
Adapter.java
import javax.xml.bind.annotation.adapters.XmlAdapter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class Adapter extends XmlAdapter<List<KeyValue>, Map<String, String>> {
@Override
public Map<String, String> unmarshal(List<KeyValue> v) throws Exception {
Map<String, String> map = new HashMap<>(v.size());
for (KeyValue keyValue : v) {
map.put(keyValue.key, keyValue.value);
}
return map;
}
@Override
public List<KeyValue> marshal(Map<String, String> v) throws Exception {
Set<String> keys = v.keySet();
List<KeyValue> results = new ArrayList<>(v.size());
for (String key : keys) {
results.add(new KeyValue(key, v.get(key)));
}
return results;
}
}
KeyValue.java 在此处放置更好的JAXB标签。
import javax.xml.bind.annotation.XmlType;
@XmlType
public class KeyValue {
public KeyValue() {
}
public KeyValue(String key, String value) {
this.key = key;
this.value = value;
}
String key;
String value;
}