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

时间:2019-01-07 11:15:55

标签: java jackson fasterxml jackson-dataformat-xml

我正在尝试将XML字符串转换为Map,下面的代码转换得很好,但是我需要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));
} 

实际输出为:

  

{状态=成功,结果= {提供商= {lastUpdated = 1545391251168}}}

预期输出为:

  

{status =成功,结果= {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>

1 个答案:

答案 0 :(得分:0)

可能有更简单的方法,但是如果没有其他效果,则可以随时创建JsonDeserializer。无论如何,我认为PropertyNamingStrategy与如何使用Map键将bean字段映射到xml / json有关,但是我可能是错的。请参阅以下内容:

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}},状态=成功}