0

есть пост запрос пример:

POST /api HTTP/1.1
Host: checkout.test.paycom.com
X-Auth: 100fe486b33784292111b7dc
Cache-Control: no-cache

{
    "id": 123,
    "method": "cards.create",
    "params": {
        "card": { "number": "4444444444444444", "expire": "0420"},
        "amount": 350000,
        "save": true
    }
}

функция:

class Service {

 static String url = 'checkout.test.paycom.com';
  static Map<String, dynamic> headers = {
    'Host': 'checkout.test.paycom.com',
    'X-Auth': '3423343243434',
    'Cache-Control': 'no-cache'
  };

  Future createCard(
      String id, String cardNumber, String expire, int amount) async {
    try {
      Map<String, dynamic> body = {
        'id': id,
        'method': 'cards.create',
        'params': {
          'card': {
            'number': cardNumber,
            'expire': expire,
          },
          'amount': amount,
        },
      };
      final response = await http.post(url, body: body, headers: headers);
      if (response.statusCode == 200) {
        final result = jsonDecode(response.body);
        List<CardModel> data = result['params']['card'];

        print(data);
      }
    } catch (e) {
      print(e.toString());
    }
    return null;
  }
}


 factory CardModel.fromJson(Map<String, dynamic> json) {
return CardModel(
  id: json['id'],
  cardNumber: json['number'],
  expire: json['expire'],
  amount: int.parse(json['amount']),
);

}

выдает ошибку type '_InternalLinkedHashMap<String, Object>' is not a subtype of type 'String' in type cast. Что делаю не так?

1 ответ 1

0

Ответ с сервера парстие не правильно (чтобы это руками не писать есть: сайт, плагин VSCode, плагин AS, кодоген):

import 'dart:convert';
import 'package:http/http.dart';

void main() {
  Service s = Service();
  s.createCard("123", "4444444444444444" , "0420", 350000);
}

class Service {
  static String url = 'checkout.test.paycom.com';
  static Map<String, dynamic> headers = {
    'Host': 'checkout.test.paycom.com',
    'X-Auth': '3423343243434',
    'Cache-Control': 'no-cache'
  };

  Future createCard(String id, String cardNumber, String expire, int amount) async {
    try {
      Map<String, dynamic> body = {
        'id': id,
        'method': 'cards.create',
        'params': {
          'card': {
            'number': cardNumber,
            'expire': expire,
          },
          'amount': amount,
          'save': true
        },
      };
      final response = await http.post(url, body: body, headers: headers);
      if (response.statusCode == 200) {
        CardModel data = CardModel.fromJson(json.decode(str));

        print(data.result.card.token);
      }
    } catch (e) {
      print(e.toString());
    }
    return null;
  }
}

class CardModel {
    CardModel({
        this.jsonrpc,
        this.id,
        this.result,
    });

    final String jsonrpc;
    final int id;
    final Result result;

    factory CardModel.fromJson(Map<String, dynamic> json) => CardModel(
        jsonrpc: json["jsonrpc"] == null ? null : json["jsonrpc"],
        id: json["id"] == null ? null : json["id"],
        result: json["result"] == null ? null : Result.fromJson(json["result"]),
    );

    Map<String, dynamic> toJson() => {
        "jsonrpc": jsonrpc == null ? null : jsonrpc,
        "id": id == null ? null : id,
        "result": result == null ? null : result.toJson(),
    };
}

class Result {
    Result({
        this.card,
    });

    final Card card;

    factory Result.fromJson(Map<String, dynamic> json) => Result(
        card: json["card"] == null ? null : Card.fromJson(json["card"]),
    );

    Map<String, dynamic> toJson() => {
        "card": card == null ? null : card.toJson(),
    };
}

class Card {
    Card({
        this.number,
        this.expire,
        this.token,
        this.recurrent,
        this.verify,
    });

    final String number;
    final String expire;
    final String token;
    final bool recurrent;
    final bool verify;

    factory Card.fromJson(Map<String, dynamic> json) => Card(
        number: json["number"] == null ? null : json["number"],
        expire: json["expire"] == null ? null : json["expire"],
        token: json["token"] == null ? null : json["token"],
        recurrent: json["recurrent"] == null ? null : json["recurrent"],
        verify: json["verify"] == null ? null : json["verify"],
    );

    Map<String, dynamic> toJson() => {
        "number": number == null ? null : number,
        "expire": expire == null ? null : expire,
        "token": token == null ? null : token,
        "recurrent": recurrent == null ? null : recurrent,
        "verify": verify == null ? null : verify,
    };
}

Как парсить array из json

Как сериализировать json

8
  • Сайт который вы дали Кодоген, нужно всегда вставлять пример ответа API? 18 июн 2020 в 6:45
  • @AndreyKhan если модели одинаковые, то можно использовать которые есть. Если разные то под каждый ответ делать свою модель.
    – MiT
    18 июн 2020 в 8:42
  • CardModel data = CardModel.fromJson(json.decode(str)) вместо str я должен вписать response.body? 22 июн 2020 в 7:38
  • @AndreyKhan да, не увидел...
    – MiT
    22 июн 2020 в 8:32
  • все равно выдает ошибку type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'Map<String, String>', но если сделать хот релоад то уже выдает ошибку сервера 22 июн 2020 в 9:42

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.