Указан json в качестве ответа, но не уверен, как его разобрать

Я использую этот код, чтобы попытаться разобрать свой ответ от платежного шлюза:

 var responseMessage = client.PostAsJsonAsync("transaction", transData).Result;
  var response = responseMessage.Content.ReadAsStringAsync().Result;
  MessageBox.Show(response);

  JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();
  var objCustomer = jsonSerializer.Deserialize<ReturnValues.RootObject>(response);

Это класс, который я пытаюсь создать:

  public class ReturnValues
  {

    public class Card
    {
      public string id { get; set; }
      public string card_type { get; set; }
      public string first_six { get; set; }
      public string last_four { get; set; }
      public string masked_card { get; set; }
      public string expiration_date { get; set; }
      public string status { get; set; }
      public string auth_code { get; set; }
      public string processor_response_code { get; set; }
      public string processor_response_text { get; set; }
      public string processor_type { get; set; }
      public string processor_id { get; set; }
      public string avs_response_code { get; set; }
      public string cvv_response_code { get; set; }
      public DateTime created_at { get; set; }
      public DateTime updated_at { get; set; }
    }

    public class Response
    {
      public Card card { get; set; }
    }

    public class BillingAddress
    {
      public string first_name { get; set; }
      public string last_name { get; set; }
      public string company { get; set; }
      public string address_line_1 { get; set; }
      public string address_line_2 { get; set; }
      public string city { get; set; }
      public string state { get; set; }
      public string postal_code { get; set; }
      public string country { get; set; }
      public string phone { get; set; }
      public string fax { get; set; }
      public string email { get; set; }
    }

    public class ShippingAddress
    {
      public string first_name { get; set; }
      public string last_name { get; set; }
      public string company { get; set; }
      public string address_line_1 { get; set; }
      public string address_line_2 { get; set; }
      public string city { get; set; }
      public string state { get; set; }
      public string postal_code { get; set; }
      public string country { get; set; }
      public string phone { get; set; }
      public string fax { get; set; }
      public string email { get; set; }
    }

    public class Data
    {
      public string id { get; set; }
      public string type { get; set; }
      public int amount { get; set; }
      public int tax_amount { get; set; }
      public bool tax_exempt { get; set; }
      public int shipping_amount { get; set; }
      public int discount_amount { get; set; }
      public string payment_adjustment_type { get; set; }
      public int payment_adjustment_value { get; set; }
      public string currency { get; set; }
      public string description { get; set; }
      public string order_id { get; set; }
      public string po_number { get; set; }
      public string ip_address { get; set; }
      public bool email_receipt { get; set; }
      public string email_address { get; set; }
      public string payment_method { get; set; }
      public Response response { get; set; }
      public string status { get; set; }
      public int response_code { get; set; }
      public string customer_id { get; set; }
      public BillingAddress billing_address { get; set; }
      public ShippingAddress shipping_address { get; set; }
      public DateTime created_at { get; set; }
      public DateTime updated_at { get; set; }
    }

    public class RootObject
    {
      public string status { get; set; }
      public string msg { get; set; }
      public Data data { get; set; }
    }
}

Мне дают такой ответ:

Я получаю это сообщение:

System.InvalidOperationException: 'Невозможно преобразовать объект типа' System.String 'в тип' Test.ReturnValues ​​+ Response '

Я не уверен, что делаю не так. Я использовал онлайн-конвертер json, чтобы получить свой класс. Кажется, это правильно.

Какие-либо предложения?

Я использовал json2csharp.com для генерации классов C #, и он придумал кое-что другое.


person ErocM    schedule 13.02.2020    source источник
comment
Спасибо! Вот и все. Как ты это разбирал? Когда я попытался использовать json в том виде, в каком он есть, он не мог выполнить синтаксический анализ. Мне пришлось использовать их пример возвращаемых данных для класса.   -  person Optional Option    schedule 13.02.2020


Ответы (2)


Хотя вроде работает. Я провел быстрое сравнение, и есть довольно много отличий. Возможно, стоит проверить.

public class ReturnValues
{
    public class Card
    {
        public string id { get; set; }
        public string card_type { get; set; }
        public string first_six { get; set; }
        public string last_four { get; set; }
        public string masked_card { get; set; }
        public string expiration_date { get; set; }
        public string response { get; set; }
        public int response_code { get; set; }
        public string auth_code { get; set; }
        public string processor_response_code { get; set; }
        public string processor_response_text { get; set; }
        public string processor_transaction_id { get; set; }
        public string processor_type { get; set; }
        public string processor_id { get; set; }
        public string avs_response_code { get; set; }
        public string cvv_response_code { get; set; }
        public object processor_specific { get; set; }
        public string created_at { get; set; }
        public string updated_at { get; set; }
    }

    public class ResponseBody
    {
        public Card card { get; set; }
    }

    public class CustomFields
    {
    }

    public class BillingAddress
    {
        public string first_name { get; set; }
        public string last_name { get; set; }
        public string company { get; set; }
        public string address_line_1 { get; set; }
        public string address_line_2 { get; set; }
        public string city { get; set; }
        public string state { get; set; }
        public string postal_code { get; set; }
        public string country { get; set; }
        public string phone { get; set; }
        public string fax { get; set; }
        public string email { get; set; }
    }

    public class ShippingAddress
    {
        public string first_name { get; set; }
        public string last_name { get; set; }
        public string company { get; set; }
        public string address_line_1 { get; set; }
        public string address_line_2 { get; set; }
        public string city { get; set; }
        public string state { get; set; }
        public string postal_code { get; set; }
        public string country { get; set; }
        public string phone { get; set; }
        public string fax { get; set; }
        public string email { get; set; }
    }

    public class Data
    {
        public string id { get; set; }
        public string user_id { get; set; }
        public string user_name { get; set; }
        public string merchant_id { get; set; }
        public string idempotency_key { get; set; }
        public int idempotency_time { get; set; }
        public string type { get; set; }
        public int amount { get; set; }
        public int base_amount { get; set; }
        public int amount_authorized { get; set; }
        public int amount_captured { get; set; }
        public int amount_settled { get; set; }
        public int amount_refunded { get; set; }
        public int payment_adjustment { get; set; }
        public int tip_amount { get; set; }
        public string settlement_batch_id { get; set; }
        public string processor_id { get; set; }
        public string processor_type { get; set; }
        public string processor_name { get; set; }
        public string payment_method { get; set; }
        public string payment_type { get; set; }
        public List<string> features { get; set; }
        public int national_tax_amount { get; set; }
        public int duty_amount { get; set; }
        public string ship_from_postal_code { get; set; }
        public string summary_commodity_code { get; set; }
        public string merchant_vat_registration_number { get; set; }
        public string customer_vat_registration_number { get; set; }
        public int tax_amount { get; set; }
        public bool tax_exempt { get; set; }
        public int shipping_amount { get; set; }
        public int surcharge { get; set; }
        public int discount_amount { get; set; }
        public string currency { get; set; }
        public string description { get; set; }
        public string order_id { get; set; }
        public string po_number { get; set; }
        public string ip_address { get; set; }
        public string transaction_source { get; set; }
        public bool email_receipt { get; set; }
        public string email_address { get; set; }
        public string customer_id { get; set; }
        public string customer_payment_type { get; set; }
        public string customer_payment_ID { get; set; }
        public string subscription_id { get; set; }
        public string referenced_transaction_id { get; set; }
        public ResponseBody response_body { get; set; }
        public CustomFields custom_fields { get; set; }
        public object line_items { get; set; }
        public string status { get; set; }
        public string response { get; set; }
        public int response_code { get; set; }
        public BillingAddress billing_address { get; set; }
        public ShippingAddress shipping_address { get; set; }
        public string created_at { get; set; }
        public string updated_at { get; set; }
        public string captured_at { get; set; }
        public object settled_at { get; set; }
    }

    public class RootObject
    {
        public string status { get; set; }
        public string msg { get; set; }
        public Data data { get; set; }
    }
}

используйте jsoup, это бесплатная структура, которая легко анализирует документ в формате json

person nickfinity    schedule 13.02.2020
comment
Я использовал то, что было у вас, но избавился от косых черт и открывающих / завершающих кавычек. Это сбивало меня с толку, когда я сначала попробовал. - person ErocM; 13.02.2020
comment
"{\" статус \ ": \" успех \ ", \" сообщение \ ": \" успех \ ", \" данные \ ": {\" id \ ": \" bp2pa41erttupu3q1eng \ ", \" user_id \ " : \ "bmibms9erttqdc2kigl0 \", \ "имя_пользователя \": \ "dev \", \ "merchant_id \": \ "asdfasdf \", \ "idempotency_key \": \ "\", \ "idempotency_time \": 0, \ "тип \": \ "продажа \", \ "сумма \": 1000, \ "базовая_ сумма \": 1000, \ "авторизованная_ сумма \": 1000, \ "сумма_слова \": 1000, \ "рассчитанная_ сумма \": 0, \ "amount_refunded \": 0, \ "payment_adjustment \": 0, \ "tip_amount \": 0, \ "set_batch_id \": \ "\", \ "processor_id \": \ "bmibnfperttqdc2kigmg \", \ "тип_процессора \": \ "tsys_sierra \", \ "имя_процессора \": \ "Кредитные карты с ключом \", \ "метод_платы \": \ "карта \", \ "тип_платы \": \ "карта \", \ "особенности \": [\ "avs \", \ "card_verification \", \ "levelii \", \ "fake_response \"], \ "national_tax_amount \": 0, \ "duty_amount \": 0, \ "ship_from_postal_code \ ": \" \ ", \" summary_commodity_code \ ": \" \ ", \" merchant_vat_registration_number \ ": \" \ ", \" customer_vat_registration_number \ ": \" \ ", \" tax_amount \ ": 0, \ "tax_exempt \": false, \ "shipping_amount \": 0, \ "доплата \": 0, \ "Discount_amount \": 0, \ "currency \": \ " usd \ ", \" description \ ": \" Это тест \ ", \" order_id \ ": \" 555555 \ ", \" po_number \ ": \" 666666 \ ", \" ip_address \ ": \ "1.1.1.1 \", \ "источник_ транзакции \": \ "api \", \ "email_receipt \": false, \ "email_address \": \ "\", \ "customer_id \": \ "\", \ "customer_payment_type \": \ "\", \ "customer_payment_ID \": \ "\", \ "subscription_id \": \ "\", \ "referenced_transaction_id \": \ "\", \ "response_body \": { \ "card \": {\ "id \": \ "bp2pa41erttupu3q1eo0 \", \ "card_type \": \ "visa \", \ "first_six \": \ "401288 \", \ "last_four \": \ "1881 \", \ "masked_card \": \ "401288 ****** 1881 \", \ "expiration_date \": \ "21/12 \", \ "response \": \ "одобрено \", \ "response_code \": 100, \ "auth_code \": \ "TAS000 \", \ "processor_response_code \": \ "00 \", \ "processor_response_text \": \ "APPROVAL TAS000 \", \ "processor_transaction_id \" : \ "000000000000000 \", \ "тип_процессора \": \ "tsys_sierra \", \ "идентификатор_процессора \": \ "bmgwgtgtherhemg \", \ "avs_response_code \": \ "M \", \ "cvv_response_code \": \ "M \", \ "специфичный для процессора \": null, \ "created_at \": \ "2020-02-13T18: 27: 28.149933095Z \", \ "updated_at \": \ "2020-02-13T18: 27: 28.19636766 9Z \ "}}, \" custom_fields \ ": {}, \" line_items \ ": null, \" status \ ": \" pending_settlement \ ", \" response \ ": \" одобрено \ ", \" response_code \ ": 100, \" billing_address \ ": {\" first_name \ ": \" John \ ", \" last_name \ ": \" Doe \ ", \" company \ ": \" \ ", \" address_line_1 \ ": \" 123 Some Street \ ", \" address_line_2 \ ": \" \ ", \" city \ ": \" Bessemer \ ", \" state \ ": \" AL \ ", \" postal_code \ ": \" 35020 \ ", \" страна \ ": \" США \ ", \" телефон \ ": \" 5555555555 \ ", \" факс \ ": \" \ ", \" электронная почта \ ": \ "[email protected] \"}, \ "адрес доставки \": {\ "first_name \": \ "\", \ "last_name \": \ "\", \ "company \": \ "\", \ "адрес_строка_1 \": \ "\", \ "строка_адреса_2 \": \ "\", \ "город \": \ "\", \ "штат \": \ "\", \ "почтовый_код \": \ "\", \ "страна \": \ "\", \ "телефон \": \ "\", \ "факс \": \ "\", \ "электронная почта \": \ "\"}, \ "created_at \": \ "2020-02-13T18: 27: 28. 104845544Z \ ", \" updated_at \ ": \" 2020-02-13T18: 27: 28.200963331Z \ ", \" capture_at \ ": \" 2020-02-13T18: 27: 28.200962679Z \ ", \" Set_at \ ": null}} \ n" - person nickfinity; 13.02.2020

Во-первых, в конце строки ответа есть символ конца строки. Обрежьте это и попробуйте снова.

  `list<Element> news;
  Document doc = Jsoup.connect("https://en.wikipedia.org/").get();
  log(doc.title());
  Elements newsHeadlines = doc.select("#mp-itn b a");
  for (Element headline : news) {
     log("%s\n\t%s", 
   headline.attr("title"), headline.absUrl("href"));
 }`
person anfaas1618    schedule 13.02.2020