gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 07:27:02 24 4
gpt4 key购买 nike

我正在尝试将 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));
}

实际输出为:

{Status=Success, Result={Provider={lastUpdated=1545391251168}}}

预期输出为:

{status=Success, 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}

关于java - 使用 Jackson 将 XML 转换为 Map,Key 应小写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54073320/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com