0

我有一个要求,我需要从 API 转换 JSON 响应并将其作为 XML 发送到最终客户端。

我能够从 API 成功接收 JSON(粘贴在下面的输出),但无法使用 ObjectMapper 将其转换为 Java 对象。我没有收到任何错误;但是当我返回“GetCardInfo”对象时它为空。

我曾尝试通过谷歌搜索,但无法找到它不起作用的原因。如果有人可以帮助我理解我的代码有什么问题,那将是一个很大的帮助。

import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;
import java.lang.Object;

import javax.annotation.Resource;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.ws.Response;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpStatus;
import org.json.JSONObject;
import org.json.XML;
import org.slf4j.ext.XLogger;
import org.slf4j.ext.XLoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;

import com.bhn.webservice.ivr.CardActivationResponse;
import com.bhn.webservice.ivr.CardInfo;
import com.bhn.webservice.ivr.ErrorDetails;
import com.bhn.webservice.ivr.GetCardInfo;
import com.bhn.webservice.ivr.GetCardInfoReceiveJSONResponse;
import com.bhn.webservice.ivr.GetCardInfoRequest;
import com.bhn.webservice.ivr.GetCardInfoResponse;
import com.bhn.webservice.ivr.GetCardInfoSendJSONRequest;
import com.bhn.webservice.ivr.GetCardTransactionsReceiveJSONResponse;
import com.bhn.webservice.ivr.GetCardTransactionsRequest;
import com.bhn.webservice.ivr.GetCardTransactionsResponse;
import com.bhn.webservice.ivr.GetCardTransactionsSendJSONRequest;
import com.bhn.webservice.ivr.IVRKPNResponse;
import com.bhn.webservice.ivr.IVRResponse;
import com.bhn.webservice.ivr.IVRWrapperConstants;
import com.bhn.webservice.ivr.IVRWrapperResponse;
import com.bhn.webservice.ivr.RequestContext;
import com.bhn.webservice.ivr.VerifyCardConvertResponse;
import com.bhn.webservice.ivr.VerifyCardHolderReceiveJSONResponse;
import com.bhn.webservice.ivr.VerifyCardHolderRequest;
import com.bhn.webservice.ivr.VerifyCardHolderResponse;
import com.bhn.webservice.ivr.VerifyCardHolderSendJSONRequest;
import com.bhn.webservice.ivr.VerifyCardReceiveJSONResponse;
import com.bhn.webservice.ivr.VerifyCardRequest;
import com.bhn.webservice.ivr.VerifyCardResponse;
import com.bhn.webservice.ivr.VerifyCardSendJSONRequest;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
  //XML mapper.
    ObjectMapper mapper = new XmlMapper();
                   mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,
                        false);
                mapper.enable(SerializationFeature.INDENT_OUTPUT);
GetCardInfo gci = mapper.readValue(JSONResponse.toString(),GetCardInfo.class);

下面是 JSONResponse.toString() 的输出

{
  "transactionId" : "RNQFBKGPZ4M18PLZJA4BDGC32W",
  "isCompleted" : true,
  "percentComplete" : "100",
  "card" : {
    "id" : "1000000000000098718",
    "bin" : "451129",
    "proxyCardNumber" : "603953510161946xxxx",
    "isActive" : false,
    "isRegistered" : false,
    "expirationDate" : "2017-06-30T23:59:59.000+0000",
    "serviceCode" : "121",
    "balances" : {
      "openingBalance" : "5000",
      "closingBalance" : "5000",
      "pendingBalance" : "5000",
      "currencyCode" : "USD"
    },
    "status" : "OPEN",
    "statusReason" : "NONE",
    "provisionType" : "PHYSICAL",
    "accountStatus" : "OPEN",
    "accountStatusReason" : "NONE",
    "product" : {
      "id" : "1000000000000000415",
      "name" : "EXM Visa Corp LAP",
      "isActive" : "true",
      "productIdentifier" : "07675023660",
      "bin" : "451129",
      "issuer" : "MetaBank"
    }
  }
} 

下面是 GetCardInfo 类

public class GetCardInfo {

    @XmlElement(name = "transactionId", required = true)
    public String transactionId;
    @XmlElement(name = "isCompleted", required = true)
    public Boolean isCompleted;
    @XmlElement(name = "percentComplete", required = true)
    public String percentComplete;

    @XmlElement(name = "card", required = true)
    public Card card; //Parent for remaining data

    public static class Card {
        @XmlElement(name = "id", required = true)
        public String id;
        @XmlElement(name = "bin", required = true)
        public String bin;
        @XmlElement(name = "proxyCardNumber", required = true)
        public String proxyCardNumber;
        @XmlElement(name = "isActive", required = true)
        public Boolean isActive;
        @XmlElement(name = "isRegistered", required = true)
        public Boolean isRegistered;
        @XmlElement(name = "expirationDate", required = true, type = String.class)
        @XmlJavaTypeAdapter(Adapter1 .class)
        @XmlSchemaType(name = "dateTime")
        public Date expirationDate;
        @XmlElement(name = "serviceCode", required = true)
        public String serviceCode;
        @XmlElement(name = "balances", required = true)
        public Balances balances; //Parent for balances data
        @XmlElement(name = "status", required = true)
        public String status;
        @XmlElement(name = "statusReason", required = true)
        public String statusReason;
        @XmlElement(name = "provisionType", required = true)
        public String provisionType;
        @XmlElement(name = "accountStatus", required = true)
        public String accountStatus;
        @XmlElement(name = "accountStatusReason", required = true)
        public String accountStatusReason;
        @XmlElement(name = "product", required = true)
        public Product product; 

        @Override
        public String toString() {
            return "Card [id=" + id + ", bin=" + bin + ", "
                    + "proxyCardNumber=" + proxyCardNumber + ", isActive=" + isActive
                    + ", isRegistered=" + isRegistered + ", expirationDate=" + expirationDate
                    + ", serviceCode=" + serviceCode + ", balances=" + balances
                    + ", status=" + status + ", statusReason=" + statusReason
                    + ", provisionType=" + provisionType + ", accountStatus=" + accountStatus
                    + ", accountStatusReason=" + accountStatusReason + ", product=" + product + "]";
        }
    }

    public static class Balances {
        @XmlElement(name = "openingBalance", required = true)
        public String openingBalance;
        @XmlElement(name = "closingBalance", required = true)
        public String closingBalance;
        @XmlElement(name = "pendingBalance", required = true)
        public String pendingBalance;
        @XmlElement(name = "currencyCode", required = true)
        public String currencyCode;

        @Override
        public String toString() {
            return "Balance [openingBalance=" + openingBalance + ", closingBalance=" + closingBalance + ", "
                    + "pendingBalance=" + pendingBalance + ", currencyCode=" + currencyCode + "]";
        }
    }

    public static class Product {
        @XmlElement(name = "id", required = true)
        public String id;
        @XmlElement(name = "name", required = true)
        public String name;
        @XmlElement(name = "isActive", required = true)
        public String isActive;
        @XmlElement(name = "productIdentifier", required = true)
        public String productIdentifier;
        @XmlElement(name = "bin", required = true)
        public String bin;
        @XmlElement(name = "issuer", required = true)
        public String issuer;

        @Override
        public String toString() {
            return "Card [id=" + id + ", bin=" + bin + ", "
                    + "name=" + name + ", isActive=" + isActive
                    + ", productIdentifier=" + productIdentifier + ", issuer=" + issuer + "]";
        }
    }

    @Override
    public String toString() {
        return "GetCardInfo [transactionId=" + transactionId
                + ", isCompleted=" + isCompleted
                + ", percentComplete=" + percentComplete
                + ", card=" + card + "]";
    }   

}

编辑:我为 IOException 设置了一个 catch 块,发现我低于 IOException。这意味着我的 JSON 字符串有问题。

在下面添加了我的 POM.xml。还在上面为具有 ObjectMapper 的 Java 文件添加了导入。

catch (IOException e) { logger.error("IOException - ", e.getMessage()); e.printStackTrace(); }

IOException -  com.ctc.wstx.exc.WstxUnexpectedCharException: Unexpected character '{' (code 123) in prolog; expected '<'
 at [row,col {unknown-source}]: [1,1]

Pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

    <modelVersion>4.0.0</modelVersion>

    <organization>
        <name>xxx</name>
        <url></url>
    </organization>

    <parent>
        <groupId>com.bhn.poms</groupId>
        <artifactId>component-parent-pom</artifactId>
        <version>2.17</version>
        <relativePath />
    </parent>

    <artifactId>ivr-wrapper-service</artifactId>
    <groupId>com.bhn.webservice</groupId>
    <version>1.2.26-SNAPSHOT</version>
    <name>IVR Wrapper Service Implementation</name>
    <description>This project defines the java implementation for this service.</description>

    <properties>
        <bhn-entity-management-version>2.32</bhn-entity-management-version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>com.bhn.webservice</groupId>
            <artifactId>entity-management-service</artifactId>
            <version>${bhn-entity-management-version}</version>
        </dependency>
        <dependency>
            <groupId>com.bhn.webservice</groupId>
            <artifactId>ivr-wrapper-domain-model</artifactId>
            <version>${project.version}</version>
        </dependency>
        <dependency>
            <groupId>com.bhn.webservice</groupId>
            <artifactId>web-service-client</artifactId>
            <version>2.41</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>fluent-hc</artifactId>
            <version>4.5</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.dataformat</groupId>
            <artifactId>jackson-dataformat-xml</artifactId>
            <version>2.6.3</version>
        </dependency>
        <dependency>
            <groupId>org.codehaus.woodstox</groupId>
            <artifactId>woodstox-core-asl</artifactId>
            <version>4.4.1</version>
        </dependency>
        <dependency>
            <groupId>org.json</groupId>
            <artifactId>json</artifactId>
            <version>20160212</version>
        </dependency>
    </dependencies>

    <scm>
        <connection>scm:git:ssh://git@xxx.com:7999/custom/ivrwrapper.git</connection>
        <developerConnection>scm:git:ssh://git@xxx.com:7999/custom/ivrwrapper.git</developerConnection>
        <tag>HEAD</tag>
    </scm>

</project>

编辑:基于@minus 评论,我已将我的 JSON 字符串转换为 XML 字符串,如下所示

JSONObject json = new JSONObject(JSONResponse.toString());
                xml = XML.toString(json);
                logger.info("GetCardInfo XML Response for KPN API: {} ", xml);  

日志显示它已成功转换为 XML。

<percentComplete>100</percentComplete><transactionId>FL2YTNR86KARMVYWWVK3410F4W</transactionId><card><product><productIdentifier>07675023660</productIdentifier><bin>451129</bin><name>EXM Visa Corp LAP</name><id>1000000000000000415</id><isActive>true</isActive><issuer>MetaBank</issuer></product><serviceCode>121</serviceCode><bin>451129</bin><isActive>false</isActive><proxyCardNumber>6039535101619469382</proxyCardNumber><accountStatusReason>NONE</accountStatusReason><accountStatus>OPEN</accountStatus><balances><pendingBalance>5000</pendingBalance><closingBalance>5000</closingBalance><openingBalance>5000</openingBalance><currencyCode>USD</currencyCode></balances><statusReason>NONE</statusReason><provisionType>PHYSICAL</provisionType><isRegistered>false</isRegistered><id>1000000000000098718</id><expirationDate>2017-06-30T23:59:59.000+0000</expirationDate><status>OPEN</status></card><isCompleted>true</isCompleted> 

接下来我使用下面的代码将 XML 字符串反序列化回 Java 对象。但是反序列化不起作用。

   GetCardInfo gci = mapper.readValue(xml, GetCardInfo.class);
                    logger.info("Test12 ", gci.toString());

现在我没有收到任何错误,但反序列化不起作用。GCI 对象中的字段为空。

4

2 回答 2

0

我对 Jackson 不是很了解,但您正在尝试使用 XML 映射器反序列化 json 文档。

杰克逊确切地告诉你,你不能用'{'开始一个xml。

您应该使用 JsonMapper 反序列化 Json,然后使用 XMLMapper 对其进行序列化。

我不知道是否可以为两者注释同一个类。

于 2017-03-13T22:54:28.123 回答
0

感谢@minus 的意见。我能够找出答案

我所需要的只是将类名添加到我的 XML 字符串中,如下所示

字符串输入 = "" + xml + ""; 之后,我能够成功反序列化。

于 2017-03-13T23:40:46.020 回答