简体   繁体   中英

get value of a key from nested Json using JObject

I am trying to get the values of the below JSON string:

{
    "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"
        }
    ]
}

I have used the below code to get it but did not work:

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"];

any suggestions?

I wold try something like this

var paymentStatus = JObject.Parse(response.Content)["PaymentStatus"][0];

string statusDescription = paymentStatus["StatusDescription"].ToString();

string merchantTxnRefNo = paymentStatus["MerchantTxnRefNo"].ToString();

or maybe you need c# classes

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; }
}

Since PaymentStatus resolves to an array, use the indexer to get the object as below

var StatusDescription = (string)jObject["PaymentStatus"] [0] ["MerchantTxnRefNo"];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM