使用Jackson将XML转换为Map,Key应为小写



我正在尝试将XML字符串转换为Map,下面的代码转换得很好,但我需要映射键应该统一(小写或大写)。

public static void main(String[] args) throws Exception {
XmlMapper xmlMapper = new XmlMapper();
xmlMapper.setPropertyNamingStrategy(PropertyNamingStrategy.LOWER_CASE);
String xml = "<Find Status="Success"><Result><Provider><lastUpdated>1545391251168</lastUpdated></Provider></Result></Find>";
System.out.println(xmlMapper.readValue(xml.getBytes(), Map.class));
} 

实际输出为:

{状态=成功,结果={提供者={上次更新=1545391251168}}}}

预期输出为:

{status=成功,result={provider={lastupdated=1545391251168}}}}

依赖项:

<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.9.8</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
<version>2.9.8</version>
</dependency>

可能有更简单的方法可以做到这一点,但如果其他方法都不起作用,您总是可以创建一个JsonDeserializer。无论如何,我认为PropertyNamingStrategy与如何将bean字段映射到xml/json有关,而不是与Map键有关,但我可能错了。参见以下内容:

public class LowerKeyDeserializer extends JsonDeserializer<Map<String, Object>> {
@Override
public Map<String, Object> deserialize(JsonParser p, DeserializationContext ctxt)
throws IOException, JsonProcessingException {
Map<String, Object> map = new HashMap<>();
JsonToken jsonToken;
String name = null;
while (null != (jsonToken = p.nextToken())) {
switch (jsonToken) {
case FIELD_NAME:
name = p.getText().toLowerCase(); // "magic" here
break;
case VALUE_STRING:
map.put(name, p.getText()); // value as it is
break;
case START_OBJECT: // and this will be a "sub"map, recursive call
map.put(name, deserialize(p, ctxt));
break;
default:
;
}
}
return map;
}
}

您需要使用JacksonXmlModule在上面注册,请参阅下面的内容:

@Test
public void test() throws JsonParseException, JsonMappingException, IOException {
JacksonXmlModule xmlModule = new JacksonXmlModule();
xmlModule.addDeserializer(Map.class, new LowerKeyDeserializer());
XmlMapper xmlMapper = new XmlMapper(xmlModule);
String xml = "<Find Status="Success"><Result><Provider><lastUpdated>1545391251168</lastUpdated></Provider></Result></Find>";
Map<?, ?> map = xmlMapper.readValue(xml.getBytes(), Map.class);
System.out.println(map);
}

这应该打印:

{result={provider={lastupdated=1545391251168}},status=Success}

相关内容

  • 没有找到相关文章

最新更新