基本上,您需要一个 xml 适配器。您可以调控 KeyValue 类上的名称,以获取所需的特定输出。
参数.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;
// Getter and setter for parametersMap
}
适配器.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;
}
//obviously needs setters/getters
String key;
String value;
}