获取Jackson XMLMapper以在代码中设置根元素名称 [英] Get Jackson XMLMapper to set root element name in code

查看:494
本文介绍了获取Jackson XMLMapper以在代码中设置根元素名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在序列化时让Jackson的XMLMapper设置根xml元素的名称?

How do I get Jackson's XMLMapper to set the name of the root xml element when serializing?

如果要序列化pojo,则有一个注释可以执行:@XmlRootElement(name ="blah").但是我正在序列化一个通用的Java类LinkedHashMap,所以我不能使用注释.

There's an annotation to do it, if you're serializing a pojo: @XmlRootElement(name="blah"). But I'm serializing a generic Java class, LinkedHashMap, so I can't use an annotation.

可能在某处设置了一些开关.翻看杰克逊代码,我看到了一个名为SerializationConfig.withRootName()的类,但是我不知道如何使用它.

There's probably some switch somewhere to set it. Poking around in Jackson code, I see a class named SerializationConfig.withRootName(), but I've no clue how to use it.

推荐答案

您可以使用

You can override the root element of the XML output using the ObjectWriter.withRootName method. Here is example:

public class JacksonXmlMapper {

    public static void main(String[] args) throws JsonProcessingException {

        Map<String, Object> map = new LinkedHashMap<String, Object>();
        map.put("field1", "v1");
        map.put("field2", 10);
        XmlMapper mapper = new XmlMapper();
        System.out.println(mapper
                .writer()
                .withRootName("root")
                .writeValueAsString(map));

    }
}

输出:

<root><field1>v1</field1><field2>10</field2></root>

这篇关于获取Jackson XMLMapper以在代码中设置根元素名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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