如何使用FasterXML库序列化POJO列表 [英] How to serialize a list of POJO using FasterXML library

查看:137
本文介绍了如何使用FasterXML库序列化POJO列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用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"/>

  1. 当我序列化电影时,我得到了这一点:

  1. When I serialize a movie I get this:

有可能得到这个吗?

<movie imdbID="tt0077687" title="The Hobbit" year="1977"><movie>

推荐答案

作为一般规则,请勿尝试直接将ListMap或数组序列化为根级值:始终使用Bean(POJO ).属性可以递归地是任何类型.

As a general rule, do not try serializing List, Maps 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆