我有一个HttpClient,它从REST Api接收json字符串。根据成功与否,返回不同的json结构。我正在使用JSON.Net库将字符串反序列化为其他类,并且代码引发错误。这是我的代码
如果成功,则json字符串为: {“ token”:“ 9416285736761111”,“ expiry”:“ 1230”,“ name”:“ ETS TEST CARS VISA”}
如果有任何错误: {“ errorCode”:“ 2”,“ errorMessage”:“无效令牌”}
我的课程是 ReadCardResponse:
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; }
}
ErrorResponse:
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:{“令牌”:“ 9416285736761111”,“到期”:“ 1230”,“名称”:“ ETS测试卡签证”} 解析CC响应时出错 在CallSite.Target(Closure,CallSite,Object) 在System.Dynamic.UpdateDelegates.UpdateAndExecute1 [T0,TRet](CallSite网站,T0 arg0)
如何将json反序列化为不同的类?
答案 0 :(得分:0)
您可以从HttpClient的响应对象中读取状态代码,然后如果它是200,则解析您的普通对象:
dynamic_ccResponse = JsonConvert.DeserializeObject<ReadCardResponse>(ccResultJson);
,如果它是4xx或5xx代码解析错误对象:
dynamic_ccResponse = JsonConvert.DeserializeObject<ErrorResponse>(ccResultJson);
这确实取决于您正在正确使用实现状态代码的API。 查看此帖子以获取状态码:
How to determine a 404 response status when using the HttpClient.GetAsync()
答案 1 :(得分:0)
没关系,弄清楚了。解决方案是将反序列化的值访问为
Employees