Najeeb KHAN
Najeeb KHAN

Reputation: 41

C#: Not able to get child value from JSON string

I'm working with .net core. I hit an third-party api call with in a controller. I get response from the call. And response.Content is something like below.

"{\"GetAlertingTransactionsResult\":\"{\\\"Success\\\":true,\\\"Data\\\":[{\\\"RowNum\\\":\\\"1\\\",\\\"TransactionID\\\":\\\"611\\\",\\\"TransactionType\\\":\\\"Authorization\\\",\\\"Channel\\\":\\\"POS\\\",\\\"TxnStatusDescription\\\":\\\"Processed\\\",\\\"ErrorCode\\\":\\\"0000\\\",\\\"MID\\\":\\\"999222222222222\\\",\\\"TID\\\":\\\"99922236\\\",\\\"MerchantName\\\":\\\"NEW POS TEST MERCHANT\\\",\\\"MerchantAddress\\\":\\\"TEST ADDRESS LINE1 TEST ADDRESS LINE2\\\",\\\"TransactionAmount\\\":\\\"999.9900\\\",\\\"TipAmount\\\":\\\"0.0000\\\",\\\"DiscountAmount\\\":\\\"0.0000\\\",\\\"TotalAmount\\\":\\\"999.9900\\\",\\\"ApplicationVersion\\\":\\\"V6.0.0\\\",\\\"ApplicationID\\\":\\\"A0000007362010\\\",\\\"TxnDateTime\\\":\\\"7\\/9\\/2020 2:36:07 PM\\\",\\\"RequestDateTime\\\":\\\"7\\/9\\/2020 2:36:59 PM\\\",\\\"ResponseDateTime\\\":\\\"7\\/9\\/2020 2:36:59 PM\\\",\\\"InvoiceNumber\\\":\\\"4\\\",\\\"OldInvoiceNumber\\\":\\\"0\\\",\\\"BatchNumber\\\":\\\"15\\\",\\\"AuthNumber\\\":\\\"123\\\",\\\"AssociationName\\\":\\\"PayPakCard\\\",\\\"TC\\\":\\\"123\\\",\\\"ExpiryDate\\\":\\\"123\\\",\\\"ARQC\\\":\\\"2C254884E80D7FD2\\\",\\\"CardHolderName\\\":\\\"DEBIT\\/PAYPAK              \\\",\\\"MaskedCardNumber\\\":\\\"2205 60** **** 0476\\\",\\\"Cardtype\\\":\\\"CHIP\\\",\\\"TSI\\\":\\\"6800\\\",\\\"TVR\\\":\\\"123\\\",\\\"AppLabel\\\":\\\"PayPak Debit\\\",\\\"TotalTxnCount\\\":\\\"0\\\",\\\"TerminalSerialNumber\\\":\\\"82683858\\\",\\\"CompositeKey\\\":\\\"123\\\",\\\"PINCaptureCode\\\":\\\"1\\\",\\\"IsReprint\\\":\\\"0\\\",\\\"CustomerMobileNo\\\":null,\\\"IPAddress\\\":\\\"43.245.8.61\\\",\\\"RRN\\\":\\\"123\\\"}],\\\"TotalNumberOfRecords\\\":1}\"}"

Now I want to get values of e.g TransactionID, TransactionType and Channel etc. How would I be able to get these values in C# (.net Core)?

For reference: Code of How I'm calling a third party API.

var client = new RestClient("third-party-api-link-here");
client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.AddParameter("application/json",
            "{\r\n\"TransactionReportDTO\":\r\n{\r\n\"PageSize\":\"15\",\r\n\"PageIndex\":\"1\",\r\n\"TransactionType\":\"Authorization\",\r\n\"Channel\": \"POS\",\r\n\"MerchantName\" :\"NEW POS TEST MERCHANT\",\r\n\"TransactionAmount\" :999.9900,\r\n\"TotalAmount\":999.9900,\r\n\"MID\" :\"999222222222222\",\r\n\"TID\": \"99922236\",\r\n\"InvoiceNumber\":\"4\",\r\n\"RRN\": \"202007091436\",\r\n\"CardNumber\":\"2205600050000476\",\r\n\"TransactionStartDate\":\"2020-07-09\",\r\n\"TransactionEndDate\":\"2020-07-09\"\r\n}\r\n\r\n}"
           , ParameterType.RequestBody);
IRestResponse response = client.Execute(request)

Upvotes: 0

Views: 1696

Answers (5)

Ashwini Gupta
Ashwini Gupta

Reputation: 98

You can parse the response using JObject and JArray. You need to include Newtonsoft.Json package in project.

var jObject = JObject.Parse(responseString)["GetAlertingTransactionsResult"];
var jDataObject = JObject.Parse(jObject.ToString());
var objectArray = JArray.Parse(jDataObject["Data"].ToString());
Console.WriteLine(objectArray[0]["TransactionID"].ToString());

See code -> https://dotnetfiddle.net/wSjJYr

Optionally you can create concrete class and do.

public class Root    
{
    public string GetAlertingTransactionsResult { get; set; } 
    private SubRoot _getTransactionsResult;
    public SubRoot TransactionsResult { get =>  _getTransactionsResult ??= JsonConvert.DeserializeObject<SubRoot>(GetAlertingTransactionsResult); } 
}

public class SubRoot 
{
    public bool Success { get; set; } 
    public List<Datum> Data { get; set; } 
    public int TotalNumberOfRecords { get; set; } 
}

public class Datum    
{
    public string TransactionID { get; set; } 
}

var rObject = JsonConvert.DeserializeObject<Root>(responseString);  
var tId = rObject.TransactionsResult.Data.First().TransactionID);

See code -> https://dotnetfiddle.net/tU5NI0

Upvotes: 1

LDS
LDS

Reputation: 362

There are no TransctionID .But transction type is there

 string str = "{\r\n\"TransactionReportDTO\":\r\n{\r\n\"PageSize\":\"15\",\r\n\"PageIndex\":\"1\",\r\n\"TransactionType\":\"Authorization\",\r\n\"Channel\": \"POS\",\r\n\"MerchantName\" :\"NEW POS TEST MERCHANT\",\r\n\"TransactionAmount\" :999.9900,\r\n\"TotalAmount\":999.9900,\r\n\"MID\" :\"999222222222222\",\r\n\"TID\": \"99922236\",\r\n\"InvoiceNumber\":\"4\",\r\n\"RRN\": \"202007091436\",\r\n\"CardNumber\":\"2205600050000476\",\r\n\"TransactionStartDate\":\"2020-07-09\",\r\n\"TransactionEndDate\":\"2020-07-09\"\r\n}\r\n\r\n}";
            var jObject = JObject.Parse(str);

            string ttype = (string)jObject["TransactionReportDTO"]["TransactionType"];

Upvotes: 0

Hamid Razeghi
Hamid Razeghi

Reputation: 69

you can use online tools such as https://json2csharp.com to convert your json object to C# class and create data model out of it , then use Newtonsoft.Json to Deserialize json into c# object

Upvotes: 0

mohammad
mohammad

Reputation: 57

lets say you know all about api calls and getting string response.

for example you have got this response body from your call.

var responseBody="{
                   "userId": 1,
                   "id": 1,
                   "title": "delectus aut autem",
                   "someArray": [{"someId":3}]
                  }"

we want to fetch the object who has "someId"=3 ! we can approach the answer with multipe ways, first you can create a class with the same logic as our response body and then Convert our json string to an object of a class using Newtonsoft.Json.JsonConvert, the next way is to create a JObject class and move within the response . for the second way the example is like bellow:

var responseObject = Newtonsoft.Json.JsonConvert.DeserializeObject<JObject> 
                   (responseBody)
var o = (responseObject["someArray"] as JArray).FirstOrDefault(o=>Convert.ToInt16(o["someId"].toString()) == 3)

now o is an object from class JObject. this way you dont need to declare a class for your responseBody , but from clean code view is not the best practice

Upvotes: 0

Amirhossein Ghorbani
Amirhossein Ghorbani

Reputation: 751

You can use a third party package like Newtonsoft.Json and add it to project references by:

Install-Package Newtonsoft.Json

or dotnet cli :

dotnet add package Newtonsoft.Json

finally use the JsonConvert class and get the value:

string json = @"{
  'Name': 'Bad Boys',
  'ReleaseDate': '1995-4-7T00:00:00',
  'Genres': [
    'Action',
    'Comedy'
  ]
}";

Movie m = JsonConvert.DeserializeObject<Movie>(json);

string name = m.Name;

Upvotes: 0

Related Questions