我有一个关于通过 JAXB 编码的小问题。
目前我有一个对象的 HashMap
@XmlJavaTypeAdapter(HashMapAdapter.class)
private Map<String, Object> data;
由自定义 HashMapAdapter 编码
public class HashMapAdapter extends XmlAdapter<HashMapAdapter.AdaptedMap,
Map<String, Object>> {
@XmlRootElement
public static class AdaptedMap {
@XmlVariableNode("key")
List<Data> entries = new ArrayList<>();
}
public static class Data {
@XmlTransient
public String key;
@XmlValue
public Object value;
}
@Override
public Map<String, Object> unmarshal(AdaptedMap v) throws Exception {
throw new NotImplementedException();
}
@Override
public AdaptedMap marshal(Map<String, Object> map) throws Exception {
AdaptedMap adaptedMap = new AdaptedMap();
for (Map.Entry<String, Object> entry : map.entrySet()) {
Data data = new Data();
data.key = entry.getKey();
data.value = entry.getValue();
adaptedMap.entries.add(data);
}
return adaptedMap;
}
}
编码基于以下帖子:http://blog.bdoughan.com/2013/06/moxys-xmlvariablenode-using-maps-key-as.html
HashMap 填充有 boolean 值、长整型值或字符串值。
因此,关于博客,预期的 JSON 输出应该是:
"data": {
"booleanValue": true,
"stringValue": "test",
"longValue": 1234
}
但真正的结果是:
"data": {
"longValue": {
"type": "long",
"value": 1234
},
"stringValue": {
"type": "string",
"value": "test"
},
"booleanValue": {
"type": "boolean",
"value": true
}
}
我在 Payara Micro 174 上运行,因此在 MOXy 上作为 JAXB 提供商运行。
是否可以摆脱“类型”/“值”嵌套?
最诚挚的问候
西蒙
最佳答案
我手边没有 MOxY 实现,您可以尝试一下并告诉我它是否有效吗?
public static class Data {
@XmlTransient
public String key;
@XmlElements({
@XmlElement(type=Long.class),
@XmlElement(type=String.class),
@XmlElement(type=Boolean.class)
})
@XmlPath(".")
public Object value;
}
编辑:
使用此方法时获得的输出是:
"data": {
"stringValue": {
"value": test
},
"booleanValue": {
"value": true
},
"longValue": {
"value": 1234
}
}
遗憾的是,这与预期略有不同。
关于java - JAXB 中 HashMap<String,Object> 的自定义编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48150042/