Java使用Jackson实现JSON转XML时输出为单行无格式的问题如何解决
问题原因
- 你仅给处理JSON序列化的
ObjectMapper启用了缩进输出配置,用于输出XML的XmlMapper没有开启缩进格式化配置,默认输出的就是压缩为单行的XML内容。 - 额外说明:你输出的XML中出现了两层
<product>嵌套,是因为Products类中存储产品列表的字段没有配置XML集合外层包裹禁用,序列化时会自动为集合生成一层多余的外层标签。
解决方法
- 给
XmlMapper也添加缩进输出的配置,修改后代码如下:
public void convertJsonToXml(String jsonFilePath) { try { ObjectMapper objectMapper = new ObjectMapper(); // 原配置仅对JSON序列化生效,JSON读取阶段不需要该配置可直接删除 // objectMapper.enable(SerializationFeature.INDENT_OUTPUT); Products products = objectMapper.readValue(Paths.get(jsonFilePath).toFile(), Products.class); XmlMapper xmlMapper = new XmlMapper(); // 给XML序列化启用缩进输出 xmlMapper.enable(SerializationFeature.INDENT_OUTPUT); // 可选配置:输出标准XML声明头 <?xml version='1.0' encoding='UTF-8'?> // xmlMapper.enable(ToXmlGenerator.Feature.WRITE_XML_DECLARATION); xmlMapper.writeValue(new File("./metadata/FilteredPatches.xml"), products); } catch (JsonMappingException e1) { e1.printStackTrace(); } catch (JsonProcessingException e2) { e2.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
- 如果需要去掉多余的
<product>外层嵌套标签,在Products类的产品列表字段上添加对应注解即可:
public class Products { // 禁用集合的外层包裹标签 @JacksonXmlElementWrapper(useWrapping = false) private List<Product> product; // 其余getter、setter逻辑保持不变 }
内容的提问来源于stack exchange,提问作者Vis
相关产品推荐
相关产品推荐

