0

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)
Najeeb KHAN
  • 41
  • 10
  • https://stackoverflow.com/questions/56469046/what-is-the-equivalent-httpclient-json-post-to-this-restclient-json-post – Chetan Jul 11 '20 at 09:41
  • Does this answer your question? [Deserialize JSON into C# dynamic object?](https://stackoverflow.com/questions/3142495/deserialize-json-into-c-sharp-dynamic-object) – frankenapps Jul 11 '20 at 09:46
  • No it doesn't work for me. Do you have anyother suggestion? – Najeeb KHAN Jul 11 '20 at 10:29

5 Answers5

1

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

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
0

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;
  • Sir It's giving null values – Najeeb KHAN Jul 11 '20 at 09:56
  • What exactly give you the null value? DeserializeObject is a generic function which try to Deserialize your json content to a c# model(with public props), if it returns null, it couldn't deserialize your content. – Amirhossein Ghorbani Jul 11 '20 at 10:00
  • I don't have any class/model as like you have mentioned "Movie". I just want to extract values of TransactionId, and TransactionType and store it into a third variable. That's all what I want to do. – Najeeb KHAN Jul 11 '20 at 10:27
  • The above code is only an example, it's not your complete solution, you should create a class for your model(TransactionModel) and create public properties just like the result, for example : public int TransactionId {get; set;} public int TransactionType {get; set;} then try to deserialize response to the model: var model = JsonConvert.DeserializeObject(json); – Amirhossein Ghorbani Jul 11 '20 at 10:49
  • I have created a class with some properties like public string TransactionType {get; set;} and so on and run the following but it still gives null value on m.TransactionType **TransactionReportDTO m = JsonConvert.DeserializeObject(fakeResponse); string TransactionType = m.TransactionType;** – Najeeb KHAN Jul 11 '20 at 11:06
0

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

mohammad
  • 47
  • 1
  • 9
0

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

Hamid
  • 23
  • 7
0

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"];
LDS
  • 354
  • 3
  • 9