skip to Main Content

I have Json uploaded on a conditional server, I access this server via Dio:

Future getDataDio() async {
    try {
      final Dio dio = Dio();

      final response = await dio
          .get('https://run.mocky.io/v3/26681b8c-6581-4b8b-8fbe-3da2dc7bb785');
      return HystoryOperations.fromJson(response.data);
    } on DioError catch (e) {
      print('error log: ${e.error}');
    }
  }

Json example I’m referring to:

{
    "transaction_556505":{
        "date" : "14.01.2022 г.",
        "time" : "00:52",
        "sum" : 351.05,
        "id_order" : 556505,
        "status_order" : "paid",
        "type_order" : "payment_in"
    }, 
    "transaction_556329":{
        "date" : "14.01.2022 г.",
        "time" : "00:59",
        "sum" : 1222.96,
        "id_order" : 556329,
        "status_order" : "payment_not_completed",
        "type_order" : "payment_in"
    }, 
    "transaction_555111":{
        "date" : "13.01.2022 г.",
        "time" : "15:11",
        "sum" : 512.71,
        "id_order" : 555111,
        "status_order" : "in_processing",
        "type_order" : "payment_in"
    }
}

Json serialization has been written, in which an exception appears due to the fact that all keys in the Json request are unique:

@JsonSerializable(explicitToJson: true)
class HystoryOperations {
  final Map<String, dynamic> transaction;

  HystoryOperations({required this.transaction});

  factory HystoryOperations.fromJson(Map<String, dynamic> json) =>
      _$HystoryOperationsFromJson(json);
  Map<String, dynamic> toJson() => _$HystoryOperationsToJson(this);
}

// GENERATED CODE
HystoryOperations _$HystoryOperationsFromJson(Map<String, dynamic> json) =>
    HystoryOperations(
      transaction: json['transaction'] as Map<String, dynamic>, //Exception has occurred. _CastError (type 'Null' is not a subtype of type 'Map<String, dynamic>' in type cast)
    );

Map<String, dynamic> _$HystoryOperationsToJson(HystoryOperations instance) =>
    <String, dynamic>{
      'transaction': instance.transaction,
    };

2

Answers


  1. Chosen as BEST ANSWER

    Thanks @Prashant

    Fixed the JSON request:

    [
       {
            "date" : "14.01.2022 г.",
            "time" : "00:52",
            "sum" : 351.05,
            "id_order" : 556505,
            "status_order" : "paid",
            "type_order" : "payment_in"
        }, 
        {
            "date" : "14.01.2022 г.",
            "time" : "00:59",
            "sum" : 1222.96,
            "id_order" : 556329,
            "status_order" : "payment_not_completed",
            "type_order" : "payment_in"
        }, 
        {
            "date" : "13.01.2022 г.",
            "time" : "15:11",
            "sum" : 512.71,
            "id_order" : 555111,
            "status_order" : "in_processing",
            "type_order" : "payment_in"
        }, 
        {
            "date" : "13.01.2022 г.",
            "time" : "09:32",
            "sum" : 351.05,
            "id_order" : 556506,
            "status_order" : "paid",
            "type_order" : "refund_money"
        }
    ]
    

    and serialization with access to JSON via dio:

    @JsonSerializable(explicitToJson: true)
    class HystoryOperationsModel {
      final String date;
      final String time;
      final double sum;
      @JsonKey(name: 'id_order')
      final int idOrder;
      @JsonKey(name: 'status_order')
      final String statusOrder;
      @JsonKey(name: 'type_order')
      final String typeOrder;
    
      HystoryOperationsModel({
        required this.date,
        required this.time,
        required this.sum,
        required this.idOrder,
        required this.statusOrder,
        required this.typeOrder,
      });
    
      factory HystoryOperationsModel.fromJson(Map<String, dynamic> json) =>
          _$HystoryOperationsModelFromJson(json);
    
      Map<String, dynamic> toJson() => _$HystoryOperationsModelToJson(this);
    }
    
    Future<dynamic> getDataDioHistory = Future<dynamic>.delayed(
      const Duration(seconds: 1),
      () async {
        final Dio dio = Dio();
        try {
          final response = await dio
              .get('https://run.mocky.io/v3/b8fa7c11-8ae7-46f1-b783-6b7a2d44bc1c');
          return response.data
              .map<HystoryOperationsModel>(
                  (e) => HystoryOperationsModel.fromJson(e))
              .toList();
        } on DioError catch (e) {
          print('error log: ${e.error}');
        }
      },
    );
    

  2. Its easy.
    You have to make two model classes.
    One for List of Transactions and one for Individual transactions.
    Then you can easily Get all the items from this type of JSON.

    Your first Model Class should look like:

    class Transactions{
    String transaction = "";
    List listOfTransactionNames = [];
    List <IndividualTransactions> listOfTransaction = [];
    
    Transactions.empty();
    
    Transactions.fromJson(Map<String,dynamic> json){
    listOfTransactionNames.addAll(json.keys);
    for(int i = 0; i<json.length;i++){
          listOfTransaction.add(
          IndividualTransactions.fromJson(json[listOfTransactionNames[i]]));
        }
      }
    }
    

    And Your second Model Class looks like this.

    class IndividualTransactions {
    String date = "14.01.2022 г.";
    String time = "00:52";
    double sum = 351.05;
    int id_order = 556505;
    String status_order = "paid";
    String type_order = "payment_in";
    
    IndividualTransactions.fromJson(Map<String, dynamic> json) {
      date = json["date"];
      time = json["time"];
      sum = json["sum"];
      id_order = json["id_order"];
      status_order = json["status_order"];
      type_order = json["type_order"];
      }
    }
    

    What happening here is :-

    We are adding all keys inside a List of String named as "listOfTransactionNames " and then finding all Individual Transactions using those keys.

    After that we are using from Json method of second class to add all single values in the list of "listOfTransaction" which are found by keys inside "listOfTransactionNames".

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search