简体   繁体   English

Jackson 将列表序列化为 xml 和 json

[英]Jackson serialize list to xml & json

I have a class which I want to serialize to json and XML:我有一个要序列化为 json 和 XML 的类:

@JacksonXmlRootElement(localName = "devices")
class DeviceWrapper { // <-- this class is intended to provide root xml name

    @JacksonXmlProperty(localName = "device")
    @JacksonXmlElementWrapper(useWrapping = false)
    List<Device> devices
}

Device class is just POJO:设备类只是 POJO:

class Device {
  String field1;
  String field2;
  ...
}

Serializing of DeviceWrapper to XML working fine:将 DeviceWrapper 序列化为 XML 工作正常:

<?xml version="1.0"?>
<devices>
  <device>
    <field1>value</field1>
    <field2>value</field2>
  </device>
  <device>
    <field1>value</field1>
    <field2>value</field2>
  </device>
  ...
</devices>

but when I try serialize DeviceWrapper to json I get:但是当我尝试将 DeviceWrapper 序列化为 json 时,我得到:

{
  "devices": [
    {
      "field1": "val",
      "field2": "val"
    },
    {
      "field1": "val",
      "field2": "val"
    }
    ...
  ]
}

But I just want to get list of device values:但我只想获取设备值列表:

[
  {
    "field1": "val",
    "field2": "val"
  },
  {
    "field1": "val",
    "field2": "val"
  },
        ...
]

Ie I want to see devices only for xml as grouping element for list and do not want to see it in case of json.即我只想将 xml 的devices视为列表的分组元素,并且不想在 json 的情况下看到它。 How it can be done?怎么做?

Welcome to Stack Overflow, your problem would be solved annotating your List<Device> devices with the @JsonValue annotation, but this is not possible due to the presence of xml annotations: a way to solve is the use of the ObjectMapper#addMixIn method.欢迎使用 Stack Overflow,使用@JsonValue注释注释List<Device> devices将解决您的问题,但由于 xml 注释的存在,这是不可能的:解决方法是使用ObjectMapper#addMixIn方法。 If you define an interface like below :如果您定义如下接口:

public class DeviceWrapperModelMixIn {
    @JsonValue
    List<Device> devices;
}

You can add it to your objectmapper and obtaining the expected result without changes to the original class code:您可以将其添加到您的对象映射器中,并在不更改原始类代码的情况下获得预期结果:

mapper.addMixIn(DeviceWrapper.class, DeviceWrapperModelMixIn.class);
//it prints [{"field1":"val","field2":"val"},{"field1":"val","field2":"val"}]
System.out.println(mapper.writeValueAsString(wrapper));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM