简体   繁体   English

使用 ASP.NET Core 反序列化 HttpClient 的 Json 响应

[英]Deserilizing Json Response of HttpClient using ASP.NET Core

I am calling a third-party API with HttpClient GET Request and it works fine.我正在使用 HttpClient GET Request 调用第三方 API,它工作正常。 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这是响应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" .我想提取"status": "CAPTURED""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提前致谢

if you need just this 2 values the easiest way is如果您只需要这 2 个值,最简单的方法是

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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