[英]ObjectMapper - String JSON to java object with sublevel arrays
[英]ObjectMapper - JSON string to Java Object not working
我有一個需要從API轉換JSON響應並將其作為XML發送到最終客戶端的要求。
我能夠從API成功接收JSON(下面粘貼了輸出),但是無法使用ObjectMapper將其轉換為Java對象。 我沒有任何錯誤; 但是當我返回“ GetCardInfo”對象時,它為null。
我曾嘗試通過Google搜索,但無法找到為什么它不起作用。 如果有人可以幫助我了解我的代碼有什么問題,那將是一個很大的幫助。
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 String反序列化回Java對象。 但是反序列化不起作用。
GetCardInfo gci = mapper.readValue(xml, GetCardInfo.class);
logger.info("Test12 ", gci.toString());
現在我沒有收到任何錯誤,但是反序列化無法正常工作。 GCI對象中的字段為空。
我在Jackson方面並不大,但是您正在嘗試使用XML映射器反序列化json文檔。
傑克遜正好告訴您,您不能使用'{'開頭xml。
您應該使用JsonMapper反序列化Json,然后使用XMLMapper對其進行序列化。
我不知道是否可以為兩個注釋相同的類。
感謝@minus的投入。 我能夠找出答案
我所需要做的就是將類名添加到我的XML字符串中,如下所示
字符串輸入=“” + xml +“”; 之后,我能夠成功反序列化。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.