如何使用FasterXML库序列化POJO列表 [英] How to serialize a list of POJO using FasterXML library
问题描述
我正在使用FasterXML序列化POJO.我想序列化我的POJO列表.序列化一个信号POJO时,我得到了预期的xml(有一个问题->问题2),这是我的代码:
I'm using FasterXML to serialize POJO. I want to serialize a list of my POJO. When serialize a signle POJO I get the expected xml (there's one problem --> question 2) Here's my code:
List<Movie> movies = new ArrayList<>();
// add movies
JacksonXmlModule module = new JacksonXmlModule();
module.setDefaultUseWrapper(false);
xmlMapper = new XmlMapper(module);
xmlMapper.disable(MapperFeature.AUTO_DETECT_CREATORS,
MapperFeature.AUTO_DETECT_FIELDS,
MapperFeature.AUTO_DETECT_GETTERS,
MapperFeature.AUTO_DETECT_IS_GETTERS,
MapperFeature.AUTO_DETECT_SETTERS,
MapperFeature.USE_GETTERS_AS_SETTERS);
String xml = xmlMapper.writeValueAsString(movies);
我明白了:
<ArrayList>
<item imdbID="tt0077687" title="The Hobbit" year="1977"/>
</ArrayList>
这就是我想要的:
<movies>
<movie imdbID="tt0077687" title="The Hobbit" year="1977"/>
<movie imdbID="tt0077687" title="title2" year="1977"/>
</movies>
或
<movie imdbID="tt0077687" title="The Hobbit" year="1977"/>
<movie imdbID="tt0077687" title="title2" year="1977"/>
-
当我序列化电影时,我得到了这一点:
When I serialize a movie I get this:
有可能得到这个吗?
<movie imdbID="tt0077687" title="The Hobbit" year="1977"><movie>
推荐答案
作为一般规则,请勿尝试直接将List
,Map
或数组序列化为根级值:始终使用Bean(POJO ).属性可以递归地是任何类型.
As a general rule, do not try serializing List
, Map
s or arrays directly as the root-level value: always use a Bean (POJO). Properties may be of any types, recursively.
问题在于Java类型擦除通常会使集合和Map类型(甚至使用JSON)成为问题;但是XML还有其他问题.
The problem is that Java type erasure make things problematic for collection and Map types in general (even with JSON); but there are additional problems for XML.
因此,尽管看起来似乎不必要,但我发现以简单的Object作为根值是最安全的,即使它只是类似以下内容:
So while it may seem unnecessary, I have found it safest to have a simple Object as the root value, even if it's only something like:
public class Response {
public List<Movie> movies;
}
话虽如此,更改根元素的名称可以通过多种方式完成.一种可能性是使用Jackson注释@JsonRootName
(尽管其中有"Json",它适用于所有格式).
Having said that, to change the name of root element can be done multiple ways. One possibility is to use Jackson annotation @JsonRootName
(despite "Json" in there, it applies to all formats).
或者,您可以使用ObjectWriter
,用以下命令覆盖根名称:
Or, you can use ObjectWriter
, override root name with:
String xml mapper.writer().withRootName("movies").writeValueAsString(movies);
这篇关于如何使用FasterXML库序列化POJO列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!