您的位置:首页 > 编程语言 > Java开发

Spring MVC 集成 jackson-dataformat-xml 问题

2015-12-27 11:25 435 查看

Spring MVC 集成 jackson-dataformat-xml 问题

HttpMessageNotWritableException

Could not write content

注:如果你没有遇到这个问题,你可以直接看下面解决方法二

当我在SpringBoot集成Spring MVC中使用XML格式输出的时候,出错了,后台错误信息如下:

Failed to write HTTP message: org.springframework.http.converter.HttpMessageNotWritableException:

Could not write content: Not implemented (through reference chain: org.github.abel533.springboot.model.Country[“id”]); nested exception is com.fasterxml.jackson.databind.JsonMappingException: Not implemented (through reference chain: org.github.abel533.springboot.model.Country[“id”])

页面提示错误如下:

[code]<html>
<body>
<h1>Whitelabel Error Page</h1>
<p>
This application has no explicit mapping for /error, so you are seeing this as a fallback.
</p>
<div id="created">Sun Dec 27 10:35:49 CST 2015</div>
<div>
There was an unexpected error (type=Internal Server Error, status=500).
</div>
<div>
Could not write content: Not implemented (through reference chain: org.github.abel533.springboot.model.Country["id"]); nested exception is com.fasterxml.jackson.databind.JsonMappingException: Not implemented (through reference chain: org.github.abel533.springboot.model.Country["id"])
</div>
</body>
</html>


在默认情况下产生错误的原因只有一个,那就是启用了下面的配置:

spring.jackson.serialization.indent_output=true

这个配置会让JSON格式化输出,方便阅读。但是这个配置对XML会起到负面作用。

当输出XML的时候会使用
DefaultXmlPrettyPrinter
,这个类在调用下面方法输出XML的时候

[code]public void writeLeafElement(XMLStreamWriter2 sw,
            String nsURI, String localName, int value)
        throws XMLStreamException


会使用
Stax2WriterAdapter
类的下面方法进行输出:

[code]public void writeRaw(String text, int offset, int len) throws XMLStreamException
{
    // There is no clean way to implement this via Stax 1.0, alas...
    throw new UnsupportedOperationException("Not implemented");
}


由于这个方法没有实现,这就导致了上面错误的产生。

解决办法

方法一

由于使用下面的配置:

spring.jackson.serialization.indent_output=true

产生的问题,所以只要不启用格式化输出(默认
false
)就不会有这个问题。

方法二

参考:https://github.com/FasterXML/jackson-dataformat-xml#maven-dependency

在官方github中写了:

Also: you usually also want to make sure that XML library in use is Woodstox since it is not only faster than Stax implementation JDK provides, but also works better and avoids some known issues like adding unnecessary namespace prefixes.

jackson-dataformat-xml
默认使用下面的
stax2-api
依赖:

[code] <dependency>
     <groupId>org.codehaus.woodstox</groupId>
     <artifactId>stax2-api</artifactId>
     <version>3.1.4</version>
</dependency>


stax2-api
Stax2WriterAdapter
有些未完成的实现,还有其他的问题。并且
Woodstox
Stax
快,所以官方推荐使用
woodstox-core-asl
(Spring官方也推荐这个):

[code]<dependency>
    <groupId>org.codehaus.woodstox</groupId>
    <artifactId>woodstox-core-asl</artifactId>
    <version>4.4.1</version>
</dependency>


因此我们只要添加上面的
woodstox-core-asl
依赖即可解决问题。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: