我想将具有配置属性的 XML 文件解析为 JSON,然后将此 JSON 转换为最终结果对象。
我的班级看起来像:
@SpringBootApplication
public class AdvancedApplication {
public static void main(String[] args) {
SpringApplication.run(AdvancedApplication.class, args);
XmlMapper xmlMapper = new XmlMapper();
try {
List XMLEntries = xmlMapper
.readValue(new ClassPathResource("configuration.xml")
.getFile(), List.class);
ObjectMapper mapper = new ObjectMapper();
String jsonConfig = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(XMLEntries);
JsonNode parent = new ObjectMapper().readTree(jsonConfig);
String content = parent.path("serverport").asText();
System.out.println(content);
System.out.println(jsonConfig);
} catch (IOException e) {
e.printStackTrace();
}
}
}
在第一种情况下:
List XMLEntries = xmlMapper
.readValue(new ClassPathResource("configuration.xml")
.getFile(), List.class);
上面的方法将 JSON 包装在列表中,结果如下:
[ {
"serverport" : "9966"
}, {
"clientport" : "9999",
"serverHost" : "localhost"
} ]
但在这种情况下,我无法使用以下行读取值:
String content = parent.path("serverport").asText();
因为内容是空的。
最后,我决定以这种特殊方式将 JSON 转换为结果对象 Config:
Config configObject = mapper.readValue(jsonConfig, Config.class);
但不幸的是,我收到了一个异常,例如:
com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `com.javase.advanced.config.Config` out of START_ARRAY token
at [Source: (String)"[ {
"serverport" : "9966"
}, {
"clientport" : "9999",
"serverHost" : "localhost"
} ]"; line: 1, column: 1]
我的configuration.xml 文件如下所示:
<?xml version="1.0" encoding="UTF-8"?>
<config>
<server serverport="9966"/>
<client clientport="9999">
<serverHost>localhost</serverHost>
</client>
</config>
以及配置类如下:
@NoArgsConstructor
@Getter
@AllArgsConstructor
@ToString
public class Config {
private Server server;
private Client client;
}
我想要实现的是将configuration.xml 文件解析为JSON 并将其转换为Config 对象以创建配置类以供进一步使用。
慕雪6442864
饮歌长啸
相关分类