Home > database >  Desterilizing Json Response of HttpClient using ASP.NET Core
Desterilizing Json Response of HttpClient using ASP.NET Core

Time:11-07

I am calling a thrid-party API with HttpClient GET Request and it works fine. The response is quite complex of objects. All I want to do is to extract a specific attribute within these objects. Here is the response Json


  "creationTime": "2021-11-06T12:22:49.602Z",
  "currency": "USD",
  "customer": {
    "firstName": "xxxx"
  },
  "id": "xxxx",
  "lastUpdatedTime": "2021-11-06T12:22:51.689Z",
  "merchant": "xxx",
  "merchantAmount": 33,
  "merchantCategoryCode": "5311",
  "merchantCurrency": "USD",
  "reference": "XX",
  "result": "SUCCESS",
  "sourceOfFunds": {
    "provided": {
      "card": {
        "brand": "MASTERCARD",
        "expiry": {
          "month": "X",
          "year": "XX"
        },
        "fundingMethod": "DEBIT",
        "nameOnCard": "XXX",
        "number": "XXXXX123",
        "scheme": "MASTERCARD",
        "storedOnFile": "NOT_STORED"
      }
    },
    "type": "CARD"
  },
  "status": "CAPTURED",
  "totalAuthorizedAmount": 33,
  "totalCapturedAmount": 33,
  "totalRefundedAmount": 0,
  "transaction": [
    {
      "3DSecure": {
        "acsEci": "02",
        "authenticationToken": "XXXX XXXX=",
        "paResStatus": "Y",
        "veResEnrolled": "Y",
        "xid": "mmmXXX"
      },
      "3DSecureId": "XXX",
      "authorizationResponse": {
        "cardSecurityCodeError": "M",
        "commercialCardIndicator": "1",
        "date": "1106",
        "financialNetworkCode": "XX",
        "financialNetworkDate": "2021-11-06",
        "posData": "XXX",
        "posEntryMode": "xxx",
        "processingCode": "000000",
        "responseCode": "00",
        "stan": "22443",
        "time": "122249",
        "transactionIdentifier": "014VPH"
      },
      "customer": {
        "firstName": "XXXX"
      },
      "device": {
     
      },
      "gatewayEntryPoint": "CHECKOUT",
      "merchant": "XXXX",
      "order": {
        "amount": 33,
        "chargeback": {
          "amount": 0,
          "currency": "USD"
        },
        "creationTime": "2021-11-06T12:22:49.602Z",
        "currency": "USD",
        "description": "243",
        "id": "xxxxx",
        "lastUpdatedTime": "2021-11-06T12:22:51.689Z",
        "merchantAmount": 33,
        "merchantCategoryCode": "xxx",
        "merchantCurrency": "IQD",
        "reference": "243",
        "status": "CAPTURED",
        "totalAuthorizedAmount": 33,
        "totalCapturedAmount": 33,
        "totalRefundedAmount": 0
      },
      "response": {
        "acquirerCode": "00",
        "acquirerMessage": "Approved",
        "cardSecurityCode": {
          "acquirerCode": "M",
          "gatewayCode": "MATCH"
        },
        "gatewayCode": "APPROVED"
      },
      "result": "SUCCESS",
      "sourceOfFunds": {
        "provided": {
          "card": {
            "brand": "MASTERCARD",
            "expiry": {
              "month": "x",
              "year": "xx"
            },
            "fundingMethod": "DEBIT",
            "nameOnCard": "xxxxx",
            "number": "xxxxxx",
            "scheme": "MASTERCARD",
            "storedOnFile": "NOT_STORED"
          }
        },
        "type": "CARD"
      },
      "timeOfLastUpdate": "2021-11-06T12:22:51.689Z",
      "timeOfRecord": "2021-11-06T12:22:49.617Z",
 
    }
  ]
} 

I'd like to extract "status": "CAPTURED" and "acquirerCode": "00" . here is what I tried

  var client = new HttpClient();
            string _ContentType = "application/json";
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(_ContentType));
            client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", base64EncodedAuthenticationString);

            var _UserAgent = "d-fens HttpClient";
            client.DefaultRequestHeaders.Add("User-Agent", _UserAgent);
            HttpResponseMessage response;
            response = await client.GetAsync(api_URL);
  
            var resContent =  JsonConvert.DeserializeObject(await response.Content.ReadAsStringAsync());
 
            var content = response.Content.ReadAsStringAsync().Result;
 
            return Ok(resContent);

Extracting these values would solve the issue I'm facing. Thanks in advance

CodePudding user response:

if you need just this 2 values the easiest way is

var json = response.Content.ReadAsStringAsync().Result;

var result = JObject.Parse(json);
var status= result["status"];
var acquirerCode= result["transaction"][0]["response"]["acquirerCode"];

output

CAPTURED
00

And there is a hard way

var json = response.Content.ReadAsStringAsync().Result;

 var jsonDeserialized=JsonConvert.DeserializeObject<Data>(json);

 var status= jsonDeserialized.Status;
     
var acquirerCode=jsonDeserialized.Transaction.Select(t =>  t.Response.AcquirerCode).FirstOrDefault();

classes

public partial class Data
    {
        [JsonProperty("creationTime")]
        public DateTimeOffset CreationTime { get; set; }

        [JsonProperty("currency")]
        public string Currency { get; set; }

        [JsonProperty("customer")]
        public Customer Customer { get; set; }

        [JsonProperty("id")]
        public string Id { get; set; }

        [JsonProperty("lastUpdatedTime")]
        public DateTimeOffset LastUpdatedTime { get; set; }

        [JsonProperty("merchant")]
        public string Merchant { get; set; }

        [JsonProperty("merchantAmount")]
        public long MerchantAmount { get; set; }

        [JsonProperty("merchantCategoryCode")]
        public long MerchantCategoryCode { get; set; }

        [JsonProperty("merchantCurrency")]
        public string MerchantCurrency { get; set; }

        [JsonProperty("reference")]
        public string Reference { get; set; }

        [JsonProperty("result")]
        public string Result { get; set; }

        [JsonProperty("sourceOfFunds")]
        public SourceOfFunds SourceOfFunds { get; set; }

        [JsonProperty("status")]
        public string Status { get; set; }

        [JsonProperty("totalAuthorizedAmount")]
        public long TotalAuthorizedAmount { get; set; }

        [JsonProperty("totalCapturedAmount")]
        public long TotalCapturedAmount { get; set; }

        [JsonProperty("totalRefundedAmount")]
        public long TotalRefundedAmount { get; set; }

        [JsonProperty("transaction")]
        public Transaction[] Transaction { get; set; }
    }

    public partial class Customer
    {
        [JsonProperty("firstName")]
        public string FirstName { get; set; }
    }

    public partial class SourceOfFunds
    {
        [JsonProperty("provided")]
        public Provided Provided { get; set; }

        [JsonProperty("type")]
        public string Type { get; set; }
    }

    public partial class Provided
    {
        [JsonProperty("card")]
        public Card Card { get; set; }
    }

    public partial class Card
    {
        [JsonProperty("brand")]
        public string Brand { get; set; }

        [JsonProperty("expiry")]
        public Expiry Expiry { get; set; }

        [JsonProperty("fundingMethod")]
        public string FundingMethod { get; set; }

        [JsonProperty("nameOnCard")]
        public string NameOnCard { get; set; }

        [JsonProperty("number")]
        public string Number { get; set; }

        [JsonProperty("scheme")]
        public string Scheme { get; set; }

        [JsonProperty("storedOnFile")]
        public string StoredOnFile { get; set; }
    }

    public partial class Expiry
    {
        [JsonProperty("month")]
        public string Month { get; set; }

        [JsonProperty("year")]
        public string Year { get; set; }
    }

    public partial class Transaction
    {
        [JsonProperty("3DSecure")]
        public The3DSecure The3DSecure { get; set; }

        [JsonProperty("3DSecureId")]
        public string The3DSecureId { get; set; }

        [JsonProperty("authorizationResponse")]
        public AuthorizationResponse AuthorizationResponse { get; set; }

        [JsonProperty("customer")]
        public Customer Customer { get; set; }

        [JsonProperty("device")]
        public Device Device { get; set; }

        [JsonProperty("gatewayEntryPoint")]
        public string GatewayEntryPoint { get; set; }

        [JsonProperty("merchant")]
        public string Merchant { get; set; }

        [JsonProperty("order")]
        public Order Order { get; set; }

        [JsonProperty("response")]
        public Response Response { get; set; }

        [JsonProperty("result")]
        public string Result { get; set; }

        [JsonProperty("sourceOfFunds")]
        public SourceOfFunds SourceOfFunds { get; set; }

        [JsonProperty("timeOfLastUpdate")]
        public DateTimeOffset TimeOfLastUpdate { get; set; }

        [JsonProperty("timeOfRecord")]
        public DateTimeOffset TimeOfRecord { get; set; }
    }

    public partial class AuthorizationResponse
    {
        [JsonProperty("cardSecurityCodeError")]
        public string CardSecurityCodeError { get; set; }

        [JsonProperty("commercialCardIndicator")]
        public long CommercialCardIndicator { get; set; }

        [JsonProperty("date")]
        public long Date { get; set; }

        [JsonProperty("financialNetworkCode")]
        public string FinancialNetworkCode { get; set; }

        [JsonProperty("financialNetworkDate")]
        public DateTimeOffset FinancialNetworkDate { get; set; }

        [JsonProperty("posData")]
        public string PosData { get; set; }

        [JsonProperty("posEntryMode")]
        public string PosEntryMode { get; set; }

        [JsonProperty("processingCode")]
        public string ProcessingCode { get; set; }

        [JsonProperty("responseCode")]
        public string ResponseCode { get; set; }

        [JsonProperty("stan")]
        public long Stan { get; set; }

        [JsonProperty("time")]
        public long Time { get; set; }

        [JsonProperty("transactionIdentifier")]
        public string TransactionIdentifier { get; set; }
    }

    public partial class Device
    {
    }

    public partial class Order
    {
        [JsonProperty("amount")]
        public long Amount { get; set; }

        [JsonProperty("chargeback")]
        public Chargeback Chargeback { get; set; }

        [JsonProperty("creationTime")]
        public DateTimeOffset CreationTime { get; set; }

        [JsonProperty("currency")]
        public string Currency { get; set; }

        [JsonProperty("description")]
    
        public long Description { get; set; }

        [JsonProperty("id")]
        public string Id { get; set; }

        [JsonProperty("lastUpdatedTime")]
        public DateTimeOffset LastUpdatedTime { get; set; }

        [JsonProperty("merchantAmount")]
        public long MerchantAmount { get; set; }

        [JsonProperty("merchantCategoryCode")]
        public string MerchantCategoryCode { get; set; }

        [JsonProperty("merchantCurrency")]
        public string MerchantCurrency { get; set; }

        [JsonProperty("reference")]
        public long Reference { get; set; }

        [JsonProperty("status")]
        public string Status { get; set; }

        [JsonProperty("totalAuthorizedAmount")]
        public long TotalAuthorizedAmount { get; set; }

        [JsonProperty("totalCapturedAmount")]
        public long TotalCapturedAmount { get; set; }

        [JsonProperty("totalRefundedAmount")]
        public long TotalRefundedAmount { get; set; }
    }

    public partial class Chargeback
    {
        [JsonProperty("amount")]
        public long Amount { get; set; }

        [JsonProperty("currency")]
        public string Currency { get; set; }
    }

    public partial class Response
    {
        [JsonProperty("acquirerCode")]
        public string AcquirerCode { get; set; }

        [JsonProperty("acquirerMessage")]
        public string AcquirerMessage { get; set; }

        [JsonProperty("cardSecurityCode")]
        public CardSecurityCode CardSecurityCode { get; set; }

        [JsonProperty("gatewayCode")]
        public string GatewayCode { get; set; }
    }

    public partial class CardSecurityCode
    {
        [JsonProperty("acquirerCode")]
        public string AcquirerCode { get; set; }

        [JsonProperty("gatewayCode")]
        public string GatewayCode { get; set; }
    }

    public partial class The3DSecure
    {
        [JsonProperty("acsEci")]
        public string AcsEci { get; set; }

        [JsonProperty("authenticationToken")]
        public string AuthenticationToken { get; set; }

        [JsonProperty("paResStatus")]
        public string PaResStatus { get; set; }

        [JsonProperty("veResEnrolled")]
        public string VeResEnrolled { get; set; }

        [JsonProperty("xid")]
        public string Xid { get; set; }
    }
  • Related