Search code examples
c#jsonjson.net

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?


Solution

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