0

I'm using the json_serializable: ^6.3.1 pub package to auto generate toJson() & FromJson()

and i'm having this class

import 'package:json_annotation/json_annotation.dart';

part 'maintenance_super_request.g.dart';

@JsonSerializable()
class MaintenanceSuperRequest extends DetailedRequest {
  // String? sp_key;
  final List<String> services;
  final Unit unit;
   double? totalCost;
//This List Of Another Custom Class
  List<MaintenanceRequest> maintenanceRequestsList;

   MaintenanceSuperRequest({
    required this.maintenanceRequestsList,
    required this.services,
    required this.unit,  
    this.totalCost,
  }) ;

And this it's auto generated code by the package

// GENERATED CODE - DO NOT MODIFY BY HAND

part of 'maintenance_super_request.dart';

// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************

MaintenanceSuperRequest _$MaintenanceSuperRequestFromJson(
        Map<String, dynamic> json) =>
    MaintenanceSuperRequest(
      maintenanceRequestsList: (json['maintenanceRequestsList']
              as List<dynamic>)
          .map((e) => MaintenanceRequest.fromJson(e as Map<String, dynamic>))
          .toList(),
      services:
          (json['services'] as List<dynamic>).map((e) => e as String).toList(),
      unit: Unit.fromJson(json['unit'] as Map<String, dynamic>),
      totalCost: (json['totalCost'] as num?)?.toDouble(),
    );

Map<String, dynamic> _$MaintenanceSuperRequestToJson(
        MaintenanceSuperRequest instance) =>
    <String, dynamic>{  
      'services': instance.services,
      'unit': instance.unit,
      'totalCost': instance.totalCost,
      'maintenanceRequestsList': instance.maintenanceRequestsList,
    };

    
      factory MaintenanceSuperRequest.fromJson(Map<String, dynamic> json) =>
          _$MaintenanceSuperRequestFromJson(json);
    
      @override
      Map<String, dynamic> toJson() => _$MaintenanceSuperRequestToJson(this);
    
    }

and this is the custom class used in a list in the above class

import 'package:json_annotation/json_annotation.dart';

part 'maintenance_request.g.dart';

@JsonSerializable()

class MaintenanceRequest {
  String? spKey;
  double? cost;
  String service;
  bool isCompleted;
  MaintenanceRequest({this.spKey,this.cost,this.service='',this.isCompleted=false});



  factory MaintenanceRequest.fromJson(Map<String, dynamic> json) =>
      _$MaintenanceRequestFromJson(json);

  @override
  Map<String, dynamic> toJson() => _$MaintenanceRequestToJson(this);

}

and it's auto generated code

// GENERATED CODE - DO NOT MODIFY BY HAND

part of 'maintenance_request.dart';

// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************

MaintenanceRequest _$MaintenanceRequestFromJson(Map<String, dynamic> json) =>
    MaintenanceRequest(
      spKey: json['spKey'] as String?,
      cost: (json['cost'] as num?)?.toDouble(),
      service: json['service'] as String? ?? '',
      isCompleted: json['isCompleted'] as bool? ?? false,
    );

Map<String, dynamic> _$MaintenanceRequestToJson(MaintenanceRequest instance) =>
    <String, dynamic>{
      'spKey': instance.spKey,
      'cost': instance.cost,
      'service': instance.service,
      'isCompleted': instance.isCompleted,
    };

And I'm Using get: ^4.6.3 for state management, so in case i want to pass some data in navigation function i use this code

Get.toNamed('rootName',arguments:object.toJson());

but in case of those class when i try to retrieve the data from json using this line of code

maintenanceSuperRequest =MaintenanceSuperRequest.fromJson(Get.arguments);

it throws this error

Exception type 'MaintenanceRequest' is not a subtype of type 'Map<String, dynamic>' in type cast
Stack Trace 
#0      _$MaintenanceSuperRequestFromJson.<anonymous closure> (package:real_estate/models/requests/maintenance_req/maintenance_super_request.g.dart:14:53)
#1      MappedListIterable.elementAt (dart:_internal/iterable.dart:413:31)
#2      ListIterator.moveNext (dart:_internal/iterable.dart:342:26)
#3      new _GrowableList._ofEfficientLengthIterable (dart:core-patch/growable_array.dart:189:27)
#4      new _GrowableList.of (dart:core-patch/growable_array.dart:150:28)
#5      new List.of (dart:core-patch/array_patch.dart:51:28)
#6      ListIterable.toList (dart:_internal/iterable.dart:213:44)
#7      _$MaintenanceSuperRequestFromJson (package:real_estate/models/requests/maintenance_req/maintenance_super_request.g.dart:15:12)
#8      new MaintenanceSuperRequest.fromJson (package:real_estate/models/requests/maintenance_req/maintenance_super_request.dart:52:7)
#9      ConfirmMaintenanceCompletionController.onInit (package:real_estate/controllers/common/confirm_maintenance_completion_controller.dart:17:58)
#10     GetLifeCycleBase._onStart (package:get/get_instance/src/lifecycle.dart:66:5)
#11     InternalFinalCallback.call (package:get/get_instance/src/lifecycle.dart:12:26)
#12     GetInstance._startController (package:get/get_instance/src/get_instance.dart:253:16)
#13     GetInstance._initDependencies (package:get/get_instance/src/get_instance.dart:204:11)
#14     GetInstance.find (package:get/get_instance/src/get_instance.dart:301:17)
#15     GetInstance.put (package:get/get_instance/src/get_instance.dart:86:12)
#16     Inst.put (package:get/get_instance/src/extension_instance.dart:89:21)
#17     ConfirmMaintenanceCompletionPage.build (package:real_estate/views/common/confirm_maintenance_completion_page.dart:13:67)
#18     StatelessElement.build (package:flutter/src/widgets/framework.dart:4876:49)
#19     ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4806:15)
#20     Element.rebuild (package:flutter/src/widgets/framework.dart:4529:5)
#21     ComponentElement._firstBuild (package:flutter/src/widgets/framework.dart:4787:5)
#22     ComponentElement.mount (package:flutter/src/widgets/framework.dart:4781:5)
#23     Element.inflateWidget (package:flutter/src/widgets/framework.dart:3817:16)
#24     Element.updateChild (package:flutter/src/widgets/framework.dart:3551:18)
#25     SingleChildRenderObjectElement.mount (package:flutter/src/widgets/framework.dart:6215:14)
#26     Element.inflateWidget (package:flutter/src/widgets/framework.dart:3817:16)
#27     Element.updateChild (package:flutter/src/widgets/framework.dart:3551:18)
#28     ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4832:16)
#29     Element.rebuild (package:flutter/src/widgets/framework.dart:4529:5)
#30     ComponentElement._firstBuild (package:flutter/src/widgets/framework.dart:4787:5)

it says here 'MaintenanceRequest' is not a subtype of type 'Map<String, dynamic>' in type cast but i have no idea how to fix this.

so can any one help me with that

NOTE it works fine when i retrieve data from api using this code

(json.decode(response.body) as List)
        .map((data) => MaintenanceSuperRequest.fromJson(data))
        .toList();

UPDATE

// Data From MaintenanceSuperRequest.toJson()

 args {
//...... Some other data    
services: [Safety, Plumbing, Elevator, Landline_Satellite],

maintenanceRequestsList: [SP Key [email protected]
Cost 50.0
Service Safety
Is Completed false, SP Key [email protected]
Cost 80.0
Service Plumbing
Is Completed false, SP Key 
Cost 0.0
Service Elevator
Is Completed false, SP Key 
Cost 0.0
Service Landline_Satellite
Is Completed false]}
6
  • it because your data is List not a Map. you already use it on your last code. with map() it means you are looping the list and convert json to object Commented Dec 7, 2022 at 15:46
  • @pmatatias i thought that this line is the problem too map((e) => MaintenanceRequest.fromJson(e as Map<String, dynamic>)) .toList(), but how can i fix it. Commented Dec 7, 2022 at 16:01
  • can you provide you example data ? i guse there a nested json there Commented Dec 7, 2022 at 16:10
  • @pmatatias yes there is a nested json from both MaintenanceSuperRequest.toJson() and its list List<MaintenanceRequest> which has the MaintenanceRequest.toJson() Commented Dec 8, 2022 at 13:42
  • @pmatatias please check the example data provided in the update Commented Dec 8, 2022 at 13:42

1 Answer 1

1

I Solved my problem it was an issue due to nested json and I found out a solution on another question here

in my case it was the super class which contains a list of another class (the nested json problem) has to declear on the top this line of code

@JsonSerializable(explicitToJson: true)

this the parameter explicitToJson set to true. based on the documentation here

If true, generated toJson methods will explicitly call toJson on nested objects.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.