[英]get value of a key from nested Json using JObject
我正在嘗試獲取以下 JSON 字符串的值:
{
"PaymentStatus": [
{
"MerchantTxnRefNo": "277753772122780",
"PaymentId": "20239622798237",
"ProcessDate": "9/16/2022 8:39:00 PM",
"StatusDescription": "Transaction Success",
"TrackId": "20239622798237",
"BankRefNo": "20239622798237",
"PaymentType": "CMA",
"ErrorCode": "0",
"ProductType": "DBO",
"finalStatus": "success"
}
]
}
我已經使用下面的代碼來獲取它但沒有工作:
request.AddParameter("application/json", body,
ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
var obj = response.Content;
var TransactionObj = JObject.Parse(obj);
var jObject = Newtonsoft.Json.Linq.JObject.Parse(obj);
string StatusDescription = (string)jObject["PaymentStatus"]["StatusDescription"];
有什么建議么?
我會嘗試這樣的
var paymentStatus = JObject.Parse(response.Content)["PaymentStatus"][0];
string statusDescription = paymentStatus["StatusDescription"].ToString();
string merchantTxnRefNo = paymentStatus["MerchantTxnRefNo"].ToString();
或者你可能需要 c# 類
List<PaymentStatus> paymentStatuses = JObject.Parse(json)["PaymentStatus"]
.ToObject<List<PaymentStatus>>();
string statusDescription = paymentStatuses[0].StatusDescription;
long merchantTxnRefNo = paymentStatuses[0].MerchantTxnRefNo;
public class PaymentStatus
{
public long MerchantTxnRefNo { get; set; }
public long PaymentId { get; set; }
public DateTime ProcessDate { get; set; }
public string StatusDescription { get; set; }
public long TrackId { get; set; }
public long BankRefNo { get; set; }
public string PaymentType { get; set; }
public int ErrorCode { get; set; }
public string ProductType { get; set; }
public string finalStatus { get; set; }
}
由於 PaymentStatus 解析為數組,因此使用索引器獲取 object 如下
var StatusDescription = (string)jObject["PaymentStatus"] [0]
["MerchantTxnRefNo"];
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.