Spring Boot REST 应用程序应该接受并生成 XML 和 JSON

2024-01-01

我正在研究 Spring Boot REST API。我的应用程序应该使用并生成 XML 和 JSON。我遇到了 Jackson json Xml 依赖项。

    <groupId>com.fasterxml.jackson.dataformat</groupId>
        <artifactId>jackson-dataformat-xml</artifactId>
        <version>2.5.4</version>
    </dependency>

我将其添加到我的 pom.xml 中。现在我可以接受 xml 输入,但映射到 Java 对象时值为 null。以下是我的资源类。

@Configuration
@ImportResource("/application-context.xml")
@EnableAutoConfiguration
@ResponseBody
@RequestMapping("/match")
public class MatchResource {

    private static final Logger logger = LogManager.getLogger(MatchResource.class);

    @Autowired
    private MatchService matchService;

    @RequestMapping(method = RequestMethod.POST)
    @Consumes({MediaType.TEXT_XML,MediaType.APPLICATION_JSON})
    @Produces({MediaType.TEXT_XML,MediaType.APPLICATION_JSON})
    //@Produces( MediaType.APPLICATION_XML)
    public Response matchRequest(@RequestBody MatchRequest matchRequest,
                                 @Context HttpServletRequest headers) throws Exception {

        Response resp = null;
        MiniMatchResponse output = null;

        // Headers are store in the "headers" object. To retrieve a specific header, please take a look at the below statement
        String apiUser = headers.getHeader("Api-User");

        UUID randID = UUID.randomUUID();

        logger.info("Get Match for with ID: " + randID);

        // Get service profile from headers via MatchConstants.SERVICE_PROFILE_HEADER
        String serviceProfile = "";

        try {

            //TODO: MatchService should return MatchResponse Object

            //Json OutPut
            output = matchService.findResponse(matchRequest, serviceProfile);

            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            factory.setNamespaceAware(true);

            logger.debug("Match Request: " + matchRequest.toString());
        } catch (ErrorException e) {
            logger.error(e.getMessage(), e);
         }
         // Form Response
        resp = Response.status(200).entity(output).build();

        return resp;
    }

下面是我的请求对象

  package com.infoconnect.api.dto.Match;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;

import java.io.Serializable;
import java.util.List;

@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
public class MatchRequest implements Serializable {

    // Gets or sets the RequestType of request this represents.
    // Allowed values are "Company", "People" and "Any".
    private String requestType;
    private String name;
    private String companyName;
    private String streetAddress;
    private String streetAddress2;
    private String city;
    private String stateProvince;
    private String postalCode;
    private String country;
    private String serviceProfile;
    private String resourceType;
    private int limit;
    private Integer confidence;
    private String phone;
    private Boolean includeHistorical;
    private Boolean includeNonVerified;
    private String requestId;
    private List<String> fields;

    public String getRequestType() {
        return requestType;
    }

    public void setRequestType(String requestType) {
        this.requestType = requestType;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getCompanyName() {
        return companyName;
    }

    public void setCompanyName(String companyName) {
        this.companyName = companyName;
    }

    public String getStreetAddress() {
        return streetAddress;
    }

    public void setStreetAddress(String streetAddress) {
        this.streetAddress = streetAddress;
    }

    public String getStreetAddress2() {
        return streetAddress2;
    }

    public void setStreetAddress2(String streetAddress2) {
        this.streetAddress2 = streetAddress2;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public String getStateProvince() {
        return stateProvince;
    }

    public void setStateProvince(String stateProvince) {
        this.stateProvince = stateProvince;
    }

    public String getPostalCode() {
        return postalCode;
    }

    public void setPostalCode(String postalCode) {
        this.postalCode = postalCode;
    }

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }

    public String getServiceProfile() {
        return serviceProfile;
    }

    public void setServiceProfile(String serviceProfile) {
        this.serviceProfile = serviceProfile;
    }

    public String getResourceType() {
        return resourceType;
    }

    public void setResourceType(String resourceType) {
        this.resourceType = resourceType;
    }  

    public int getLimit() {
        return limit;
    }

    public void setLimit(int limit) {
        this.limit = limit;
    }

    public Integer getConfidence() {
        return confidence;
    }

    public void setConfidence(Integer confidence) {
        this.confidence = confidence;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public Boolean getIncludeHistorical() {
        return includeHistorical;
    }

    public void setIncludeHistorical(Boolean includeHistorical) {
        this.includeHistorical = includeHistorical;
    }

    public Boolean getIncludeNonVerified() {
        return includeNonVerified;
    }

    public void setIncludeNonVerified(Boolean includeNonVerified) {
        this.includeNonVerified = includeNonVerified;
    }

    public String getRequestId() {
        return requestId;
    }

    public void setRequestId(String requestId) {
        this.requestId = requestId;
    }

    public List<String> getFields() {
        return fields;
    }

    public void setFields(List<String> fields) {
        this.fields = fields;
    }

    @Override
    public String toString() {
        return "MatchRequest{" +
                "requestType='" + requestType + '\'' +
                ", name='" + name + '\'' +
                ", companyName='" + companyName + '\'' +
                ", streetAddress='" + streetAddress + '\'' +
                ", streetAddress2='" + streetAddress2 + '\'' +
                ", city='" + city + '\'' +
                ", stateProvince='" + stateProvince + '\'' +
                ", postalCode='" + postalCode + '\'' +
                ", country='" + country + '\'' +
                ", serviceProfile='" + serviceProfile + '\'' +
                ", resourceType='" + resourceType + '\'' +
                ", limit=" + limit +
                ", confidence=" + confidence +
                ", phone='" + phone + '\'' +
                ", includeHistorical=" + includeHistorical +
                ", includeNonVerified=" + includeNonVerified +
                ", requestId='" + requestId + '\'' +
                ", fields=" + fields +
                '}';
    }
}

JSON 请求和响应工作正常。您能帮助我如何在我的应用程序中包含 XML 请求和响应吗?


尝试添加一个@XmlRootElement(name="myRootTag")JAXB 注释以及您用作类的根标签的标签MatchRequest。在 REST 请求中同时使用 XML 和 JSON 作为传输格式,但使用 moxy 而不是 Jackson 时,我遇到了类似的问题。无论如何,正确的 JAXB 注释对于与 XML 之间的转换是必要的(XML 在这方面比 JSON 更加挑剔)。

Jackson XML 应该支持 JAXB 注释,如果这不起作用,它有一组自己的与 JAXB 不兼容的类似注释(请参阅https://github.com/FasterXML/jackson-dataformat-xml https://github.com/FasterXML/jackson-dataformat-xml and https://github.com/FasterXML/jackson-dataformat-xml/wiki/Jackson-XML-annotations https://github.com/FasterXML/jackson-dataformat-xml/wiki/Jackson-XML-annotations)

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Spring Boot REST 应用程序应该接受并生成 XML 和 JSON 的相关文章

随机推荐