【发布时间】:2019-04-05 19:19:34
【问题描述】:
我有一个从 REST Api 接收 json 字符串的 HttpClient。根据成功与否,返回不同的 json 结构。我正在使用 JSON.Net 库将字符串反序列化为不同的类,并且代码抛出错误。这是我的代码
如果成功,json 字符串将是: {"token":"9416285736761111","expiry":"1230","name":"ETS TEST CARD VISA"}
如果有任何错误: {"errorCode":"2","errorMessage":"无效令牌"}
我的课程是 读卡响应:
public class ReadCardResponse
{
public string token{get;set;}
public string expiry {get; set;}
public string name {get;set;}
public string merchid { get; set; }
public int amount { get; set; }
public string tokenize { get; set; }
public string orderId { get; set; }
}
错误响应:
public class ErrorResponse
{
public string errorCode{get;set;}
public string errorMessage{get;set;}
}
dynamic_ccResponse = JsonConvert.DeserializeObject(ccResultJson);
if ((_ccResponse.token.Length > 5) && (_ccResponse.expiry.Length >= 3))
{
_readCardResponse = new ReadCardResponse();
_replyCode = "1";
_readCardResponse.expiry = _ccResponse.expiry;
_readCardResponpse.name = _ccResponse.name;
_readCardResponse.token = _ccResponse.token;
//Use the below notation to access values
readCardResponse.expiry = _ccResponse["expiry"];
_readCardResponse.name = _ccResponse["name"];
_readCardResponse.token = _ccResponse["token"];
_readCardResponse.amount = _requestObject.amount;
_readCardResponse.orderId = _requestObject.orderId;
_readCardResponse.tokenize = "y";
}
else if (Convert.ToInt32(_ccResponse.errorCode) == 1) //timeout
{
_replyCode = "2";
}
else if (Convert.ToInt32(_ccResponse.errorCode) == 8) //cancel button was pressed on the terminal
{
_replyCode = "8";
}
返回的错误是: ReadCardResponse JSON: {"token":"9416285736761111","expiry":"1230","name":"ETS TEST CARD VISA"} 解析 cc 响应时出错 在 CallSite.Target(闭包,CallSite,对象) 在 System.Dynamic.UpdateDelegates.UpdateAndExecute1[T0,Tret](CallSite 站点,T0 arg0)
如何将 json 反序列化为不同的类?
【问题讨论】:
标签: c# serialization json.net