你能在POJO类中同时使用@XmlElement和@JsonProperty吗?

时间:2017-06-26 19:45:05

标签: java json xml jackson

我有一个json有效负载和xml有效负载,我想将两个有效负载映射到一个POJO类。一个端点返回一个json,另一个端点返回一个xml。我可以将它们组合成一个pojo类。

{
  "house": 'big',
  "has-large-house": "yes"
}

<completed-houses>
.....
</completed-houses>
public PayloadResponse(
        @JsonProperty("house") final String house,
        @JsonProperty("has-large-house") final String hasLargeHouseList,
        @XmlElement(name="completed-houses") final String completeHouses) {
    this.house = house;
    this.hasLargeHouseList = hasLargeHouseList;
    this.completeHouses = completeHouses;
}

然后是这些属性的getter和setter。

1 个答案:

答案 0 :(得分:1)

是的!您可以使用Jackson module for JAXB annotations在同一个POJO中组合Jackson和JAXB注释,以便Jackson可以理解JAXB注释,并jackson-dataformat-xml用于序列化为XML。

以下是一个例子:

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import com.fasterxml.jackson.module.jaxb.JaxbAnnotationModule;
import lombok.Data;
import lombok.NoArgsConstructor;

import javax.xml.bind.annotation.XmlElement;
import java.io.IOException;
import java.io.StringWriter;

@Data
@NoArgsConstructor
public class PayloadResponse {
    private String house;

    @JsonProperty("has-large-house")
    private boolean largeHouse;

    @XmlElement(name = "completed-houses")
    private String completedHouses;

    public static void main(String[] args) throws IOException {
        ObjectMapper xmlMapper = new XmlMapper();
        JaxbAnnotationModule module = new JaxbAnnotationModule();
        xmlMapper.registerModule(module);

        PayloadResponse response = new PayloadResponse();
        response.setHouse("The White House");
        response.setLargeHouse(true);
        response.setCompletedHouses("1600 Pennsylvania Ave.");

        StringWriter stringWriter = new StringWriter();

        // Serialize value as XML.
        xmlMapper.writeValue(stringWriter, response);
        System.out.println("XML=" + stringWriter);

        // Serialize value as JSON.
        ObjectMapper jsonMapper = new ObjectMapper();
        stringWriter.getBuffer().setLength(0);
        jsonMapper.writeValue(stringWriter, response);
        System.out.println("JSON=" + stringWriter);
    }
}

输出以下内容:

XML=<PayloadResponse>
        <house>The White House</house>
        <has-large-house>true</has-large-house>
        <completed-houses>1600 Pennsylvania Ave.</completed-houses> 
    </PayloadResponse>

JSON={"house":"The White House",
      "completedHouses":"1600 Pennsylvania Ave.",
      "has-large-house":true}