gpt4 book ai didi

java - 如何避免或重命名 jaxb 中的键和条目标签?

转载 作者:行者123 更新时间:2023-11-30 03:27:52 24 4
gpt4 key购买 nike

您好,我目前正在使用 jaxb 将我的模型保存到 xml 。我的模型有一个字符串和一个 HashMap 。所以这里的问题是,在将 hashmap 导出到 xml 时,我得到了这样的结果。

    <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<customer>
<addressMap>
<entry>
<key>col2</key>
<value>data2</value>
</entry>
<entry>
<key>col1</key>
<value>data1</value>
</entry>
</addressMap>
</customer>

所以这里我不想要这个入口标签和 key ,而不是我期望的像下面的 xml 那样的东西..

  <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<customer>
<addressMap>
<col2>data2</col2>
<col1>data1</col1>
</addressMap>
</customer>

是否可以实现这个目标

最佳答案

差不多了。我想建议更改 xml 格式。使用像 col1、col2 等元素名称是一个“坏”主意。它的结构不太好。如果您可以接受以下格式的 xml 数据,我可以给您一个示例:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<customer>
<addressMap>
<col key="col2">data2</col>
<col key="col1">data1</col>
</addressMap>
</customer>

我猜你有一个类定义如下:

@XmlRootElement
public class Customer {
@XmlElement
public Map<String,String> addressMap;
}

当使用 JAXB 编码时,它应该产生您的第一个输出。将其更改为以下内容并添加必要的类:

@XmlRootElement
public class Customer {
@XmlElement
public AddressMap addressMap;
}

public class AddressMap {
@XmlElement
public List<Column> col;
}

public class Column {
@XmlAttribute
public String key;
@XmlValue
public String value;
}

用您的数据填充它并对其进行编码,输出应该类似于我的 xml 示例。

编辑:

addressMap保留为HashMap:

使 Customer 类如下所示:

@XmlRootElement
public class Customer {
@XmlElement
@XmlJavaTypeAdapter(MapAdapter.class)
public Map<String,String> addressMap;
}

并创建类MapAdapter:

public class MapAdapter extends XmlAdapter<AddressMap, Map<String,String>> {

@Override
public AddressMap marshal(Map<String,String> map) throws Exception {
AddressMap myMap = new AddressMap();
myMap.col = new ArrayList<Column>();
for (Entry<String,String> entry : map.entrySet()) {
Column col = new Column();
col.key = entry.getKey();
col.value = entry.getValue();
myMap.col.add(col);
}
return myMap;
}

@Override
public Map<String,String> unmarshal(AddressMap myMap) throws Exception {
Map<String,String> map = new HashMap<String, String>();
for (Column col : myMap.col) {
map.put(col.key, col.value);
}
return map;
}
}

保持类 AddressMapColumn 不变。

关于java - 如何避免或重命名 jaxb 中的键和条目标签?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29747310/

24 4 0