#c# #api #asp.net-core
Вопрос:
Я вызываю сторонний API с запросом HttpClient GET, и он отлично работает. Реакция довольно сложна для объектов. Все, что я хочу сделать, это извлечь определенный атрибут из этих объектов. Вот ответ 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",
}
]
}
Я хотел бы извлечь «статус»: «ЗАХВАЧЕН» и «Код покупателя»: «00» . вот что я попробовал
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().Resu<
return Ok(resContent);
Извлечение этих значений решило бы проблему, с которой я столкнулся. Заранее спасибо
Комментарии:
1. Ваш json недействителен , пожалуйста, исправьте это. А также, какая у вас проблема? Можете ли вы получить файл json из http-запроса клиента? Или вы просто не можете десериализовать json?
Ответ №1:
если вам нужны только эти 2 значения, самый простой способ —
var json = response.Content.ReadAsStringAsync().Resu<
var result = JObject.Parse(json);
var status= result["status"];
var acquirerCode= result["transaction"][0]["response"]["acquirerCode"];
выход
CAPTURED
00
И есть трудный путь
var json = response.Content.ReadAsStringAsync().Resu<
var jsonDeserialized=JsonConvert.DeserializeObject<Data>(json);
var status= jsonDeserialized.Status;
var acquirerCode=jsonDeserialized.Transaction.Select(t => t.Response.AcquirerCode).FirstOrDefault();
классы
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; }
}