Generates utilities to aid in serializing to/from JSON.


Dart CI

Provides Dart Build System builders for handling JSON.

json_serializable Pub Package

The core package providing Generators for JSON-specific tasks.

Import it into your pubspec dev_dependencies: section.

json_annotation Pub Package

The annotation package which has no dependencies.

Import it into your pubspec dependencies: section.

checked_yaml Pub Package

Generate more helpful exceptions when decoding YAML documents using package:json_serializable and package:yaml.

Import it into your pubspec dependencies: section.


An example showing how to set up and use json_serializable and json_annotation.

  • Nested Generics

    Nested Generics

    i think this his highly related to this issue

    but i have some trouble using it for my needs. I either use it wrong or it is currently not possible.

    this is an example of what i want to parse

      "status": "success",
      "message": null,
      "code": 0,
      "data": {
        "timestamp": 0,
        "result": [
            "id": 409,
            "active": true,
            "accessToken": "12345_abc",

    and here the corresponding classes

    class WsResponse<T> extends Object with _$WsResponseSerializerMixin<T> {
      String status;
      String message;
      int code;
      @JsonKey(fromJson: _dataFromJson, toJson: _dataToJson)
      WsData<T> data;
      WsResponse({this.status, this.message, this.code,});
      factory WsResponse.fromJson(Map<String, dynamic> json) => _$WsResponseFromJson<T>(json);

    here i have an outer "class" with status message and code that works like every ordinary class.

    class WsData<T> extends Object with _$WsDataSerializerMixin<T> {
      int timestamp;
      @JsonKey(fromJson: _resultFromJson, toJson: _resultToJson)
      List<T> result;
      WsData({this.timestamp, this.result});
      factory WsData.fromJson(Map<String, dynamic> json) => _$WsDataFromJson<T>(json);
    class WsLogin extends Object with _$WsLoginSerializerMixin {
      int id;
      bool active;
      String accessToken;
      WsLogin({,, this.accessToken,});
      factory WsLogin.fromJson(Map<String, dynamic> json) => _$WsLoginFromJson(json);

    I omitted the fromJson etc. definitions because i don't know how to express them right either (may be the part where i am wrong)

    but if i try _dataFromJson for example

    WsData<T> _dataFromJson<T>(Map<String, dynamic> input) {
      return input['data'] as WsData<T>;

    i get an error with

    [SEVERE] json_serializable on lib/webservice/webservice.dart:
    Error running JsonSerializableGenerator
    Error with `@JsonKey` on `data`. The `fromJson` function `_dataFromJson` return type `WsData<T>` is not compatible with field type `WsData<T>`.
      WsData<T> data;

    which is surprising for me at first. Omitting the @JsonKey annotations does not help either as i think its necessary for generics. But i don't know how to express my intent here.

    My intent is to use it like this

    var wsLoginResp = new WsResponse<WsLogin>.fromJson(json.decode(resp));  
    opened by pythoneer 29
  • Failed to recognize `json_annotation` from packages after 6.0.0

    Failed to recognize `json_annotation` from packages after 6.0.0


    Use json_annotation in a package with export is no longer valid after json_serializable 6.0.0 since the build_runner will complain the error:

    You are missing a required dependency on json_annotation in the "dependencies" section of your pubspec with a lower bound of at least "4.3.0".

    Step to reproduce

    1. Clone the project
    2. Run build_runner build in the project_a with no issues.
    3. Change the json_serializable dependency in both package and project to 6.0.0.
    4. Change the json_annotation to 4.3.0 in the base package, but not with the project.
    5. Rerun build_runner build and the error occurred.


    Flutter: 2.5.3

    opened by AlexV525 28
  • New Enums throws a [SEVERE] error

    New Enums throws a [SEVERE] error


    New flutter version 3.0.0 with dart version 2.17.0 has introduced enhanced enums. I use one of this enums for some class which gets converted into json/ from json.

    Here you can have a sample:

    enum MyExample {
      example0('example0', ExampleWidget0()),
      example1('example1', ExampleWidget1()),
      example2('example2', ExampleWidget2()),
      example3('example3', ExampleWidget3()),
      example4('example4', ExampleWidget4());
      const MyExample(this.value1, this.value2);
      final String value1;
      final Widget value2;
      String toString() => '$name: [$value1][$value2]';

    Now when I run the build runner I get this error:

    [SEVERE] json_serializable:json_serializable on lib/my_example_file.dart:
    This builder requires Dart inputs without syntax errors.
    However, package:example/my_example_file.dart (or an existing part) contains the following errors.
    my_example_file.dart:2:11: Expected to find '}'.
    Try fixing the errors and re-running the build.

    flutter --version


    Flutter 3.0.0 • channel stable • Framework • revision ee4e09cce0 (2 days ago) • 2022-05-09 16:45:18 -0700 Engine • revision d1b9a6938a Tools • Dart 2.17.0 • DevTools 2.12.2

    State: needs info 
    opened by cgutierr-zgz 27
  • NoSuchMethodError: The getter 'definingUnit' was called on null.

    NoSuchMethodError: The getter 'definingUnit' was called on null.

    Using flutter 1.22.3, when I run "flutter pub run build_runner build" I receive the following:

    [SEVERE] json_serializable:json_serializable on lib/arguments/customers_screen_arguments.dart:
    NoSuchMethodError: The getter 'definingUnit' was called on null.
    Receiver: null
    Tried calling: definingUnit
    #0      Object.noSuchMethod (dart:core-patch/object_patch.dart:51:5)
    #1      LinkedElementFactory.isLibraryUri (package:analyzer/src/summary2/linked_element_factory.dart:133:28)
    #2      LibraryContext.isLibraryUri (package:analyzer/src/dart/analysis/library_context.dart:97:27)
    #3      LibraryAnalyzer._isLibrarySource (package:analyzer/src/dart/analysis/library_analyzer.dart:522:25)
    #4      LibraryAnalyzer._resolveDirectives (package:analyzer/src/dart/analysis/library_analyzer.dart:562:36)
    #5      LibraryAnalyzer.analyzeSync (package:analyzer/src/dart/analysis/library_analyzer.dart:136:5)
    #6      LibraryAnalyzer.analyze (package:analyzer/src/dart/analysis/library_analyzer.dart:107:12)
    #7      AnalysisDriver._computeAnalysisResult2.<anonymous closure> (package:analyzer/src/dart/analysis/driver.dart:1317:63)
    #8 (package:analyzer/src/dart/analysis/performance_logger.dart:32:15)
    #9      AnalysisDriver._computeAnalysisResult2 (package:analyzer/src/dart/analysis/driver.dart:1294:20)
    #10     AnalysisDriver._computeAnalysisResult.<anonymous closure> (package:analyzer/src/dart/analysis/driver.dart:1247:14)
    #11     _rootRun (dart:async/zone.dart:1190:13)
    #12 (dart:async/zone.dart:1093:19)
    #13     _runZoned (dart:async/zone.dart:1630:10)
    #14     runZoned (dart:async/zone.dart:1550:10)
    #15     NullSafetyUnderstandingFlag.enableNullSafetyTypes (package:analyzer/dart/element/null_safety_understanding_flag.dart:42:12)
    #16     AnalysisDriver._computeAnalysisResult (package:analyzer/src/dart/analysis/driver.dart:1246:40)
    #17     AnalysisDriver._computeErrors (package:analyzer/src/dart/analysis/driver.dart:1372:41)
    #18     AnalysisDriver.performWork (package:analyzer/src/dart/analysis/driver.dart:979:20)
    #19     AnalysisDriverScheduler._run (package:analyzer/src/dart/analysis/driver.dart:2013:24)
    <asynchronous suspension>
    #20     AnalysisDriverScheduler.start (package:analyzer/src/dart/analysis/driver.dart:1936:5)
    #21     analysisDriver (package:build_resolvers/src/analysis_driver.dart:62:13)
    #22     AnalyzerResolvers._ensureInitialized.<anonymous closure> (package:build_resolvers/src/resolver.dart:306:26)
    <asynchronous suspension>
    #23     AnalyzerResolvers._ensureInitialized.<anonymous closure> (package:build_resolvers/src/resolver.dart)
    #24     AnalyzerResolvers._ensureInitialized (package:build_resolvers/src/resolver.dart:309:6)
    #25     AnalyzerResolvers.get (package:build_resolvers/src/resolver.dart:314:11)
    #26     PerformanceTrackingResolvers.get.<anonymous closure> (package:build_runner_core/src/performance_tracking/performance_tracking_resolvers.dart:19:58)
    #27     _NoOpBuilderActionTracker.trackStage (package:build_runner_core/src/generate/performance_tracker.dart:302:15)
    #28     PerformanceTrackingResolvers.get (package:build_runner_core/src/performance_tracking/performance_tracking_resolvers.dart:19:16)
    #29     BuildStepImpl.resolver (package:build/src/builder/build_step_impl.dart:74:54)
    #30 (package:source_gen/src/builder.dart:72:32)
    #31     runBuilder.buildForInput (package:build/src/generate/run_builder.dart:55:21)
    #32     MappedListIterable.elementAt (dart:_internal/iterable.dart:417:31)
    #33     ListIterator.moveNext (dart:_internal/iterable.dart:343:26)
    #34     Future.wait (dart:async/future.dart:406:26)
    #35     runBuilder.<anonymous closure> (package:build/src/generate/run_builder.dart:61:36)
    #36     _rootRun (dart:async/zone.dart:1190:13)
    #37 (dart:async/zone.dart:1093:19)
    #38     _runZoned (dart:async/zone.dart:1630:10)
    #39     runZonedGuarded (dart:async/zone.dart:1618:12)
    #40     runZoned (dart:async/zone.dart:1547:12)
    #41     scopeLogAsync (package:build/src/builder/logging.dart:26:3)
    #42     runBuilder (package:build/src/generate/run_builder.dart:61:9)
    #43     _SingleBuild._runForInput.<anonymous closure>.<anonymous closure>.<anonymous closure> (package:build_runner_core/src/generate/build_impl.dart:485:19)
    #44     _NoOpBuilderActionTracker.trackStage (package:build_runner_core/src/generate/performance_tracker.dart:302:15)
    #45     _SingleBuild._runForInput.<anonymous closure>.<anonymous closure> (package:build_runner_core/src/generate/build_impl.dart:483:23)
    <asynchronous suspension>
    #46     _SingleBuild._runForInput.<anonymous closure>.<anonymous closure> (package:build_runner_core/src/generate/build_impl.dart)
    #47     NoOpTimeTracker.track (package:timing/src/timing.dart:222:44)
    #48     _SingleBuild._runForInput.<anonymous closure> (package:build_runner_core/src/generate/build_impl.dart:440:22)
    #49     Pool.withResource (package:pool/pool.dart:127:28)
    <asynchronous suspension>
    #50     _SingleBuild._runForInput (package:build_runner_core/src/generate/build_impl.dart:436:17)
    #51     _SingleBuild._runBuilder.<anonymous closure> (package:build_runner_core/src/generate/build_impl.dart:374:38)
    #52     MappedIterator.moveNext (dart:_internal/iterable.dart:392:20)
    #53     Future.wait (dart:async/future.dart:406:26)
    #54     _SingleBuild._runBuilder (package:build_runner_core/src/generate/build_impl.dart:373:36)
    #55     _SingleBuild._runPhases.<anonymous closure>.<anonymous closure> (package:build_runner_core/src/generate/build_impl.dart:319:20)
    <asynchronous suspension>
    #56     _SingleBuild._runPhases.<anonymous closure>.<anonymous closure> (package:build_runner_core/src/generate/build_impl.dart)
    #57     _NoOpBuildPerformanceTracker.trackBuildPhase (package:build_runner_core/src/generate/performance_tracker.dart:184:15)
    #58     _SingleBuild._runPhases.<anonymous closure> (package:build_runner_core/src/generate/build_impl.dart:315:47)
    #59     NoOpTimeTracker.track (package:timing/src/timing.dart:222:44)
    #60     _SingleBuild._runPhases (package:build_runner_core/src/generate/build_impl.dart:309:32)
    #61     logTimedAsync (package:build_runner_core/src/logging/logging.dart:25:30)
    #62     _SingleBuild._safeBuild.<anonymous closure> (package:build_runner_core/src/generate/build_impl.dart:266:26)
    #63     _rootRun (dart:async/zone.dart:1190:13)
    #64 (dart:async/zone.dart:1093:19)
    #65     _runZoned (dart:async/zone.dart:1630:10)
    #66     runZonedGuarded (dart:async/zone.dart:1618:12)
    #67     runZoned (dart:async/zone.dart:1547:12)
    #68     _SingleBuild._safeBuild (package:build_runner_core/src/generate/build_impl.dart:261:5)
    #69 (package:build_runner_core/src/generate/build_impl.dart:208:24)
    #70 (package:build_runner_core/src/generate/build_impl.dart:94:56)
    #71 (package:build_runner_core/src/generate/build_runner.dart:25:14)
    #72     build (package:build_runner/src/generate/build.dart:107:21)
    <asynchronous suspension>
    #73     BuildCommand._run (package:build_runner/src/entrypoint/build.dart:35:24)
    #74<anonymous closure> (package:build_runner/src/entrypoint/build.dart:31:15)
    #75     _rootRun (dart:async/zone.dart:1190:13)
    #76 (dart:async/zone.dart:1093:19)
    #77     _runZoned (dart:async/zone.dart:1630:10)
    #78     runZoned (dart:async/zone.dart:1550:10)
    #79     withEnabledExperiments (package:build/src/experiments.dart:18:5)
    #80 (package:build_runner/src/entrypoint/build.dart:30:12)
    #81     CommandRunner.runCommand (package:args/command_runner.dart:197:27)
    #82<anonymous closure> (package:args/command_runner.dart:112:25)
    #83     new Future.sync (dart:async/future.dart:223:31)
    #84 (package:args/command_runner.dart:112:14)
    #85     run (package:build_runner/src/entrypoint/run.dart:25:31)
    <asynchronous suspension>
    #86     main (file:///C:/_eic/app/eic_app_front/.dart_tool/build/entrypoint/build.dart:27:22)
    #87     _startIsolate.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:297:32)
    #88     _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:168:12)
    package:analyzer/src/dart/analysis/driver.dart 1347:9                                         AnalysisDriver._computeAnalysisResult2.<fn>
    package:analyzer/src/dart/analysis/performance_logger.dart 32:15                    
    package:analyzer/src/dart/analysis/driver.dart 1294:20                                        AnalysisDriver._computeAnalysisResult2
    package:analyzer/src/dart/analysis/driver.dart 1247:14                                        AnalysisDriver._computeAnalysisResult.<fn>
    dart:async                                                                                    runZoned
    package:analyzer/dart/element/null_safety_understanding_flag.dart 42:12                       NullSafetyUnderstandingFlag.enableNullSafetyTypes
    package:analyzer/src/dart/analysis/driver.dart 1246:40                                        AnalysisDriver._computeAnalysisResult
    package:analyzer/src/dart/analysis/driver.dart 1372:41                                        AnalysisDriver._computeErrors
    package:analyzer/src/dart/analysis/driver.dart 979:20                                         AnalysisDriver.performWork
    package:analyzer/src/dart/analysis/driver.dart 2013:24                                        AnalysisDriverScheduler._run
    package:analyzer/src/dart/analysis/driver.dart 1936:5                                         AnalysisDriverScheduler.start
    package:build_resolvers/src/analysis_driver.dart 62:13                                        analysisDriver
    package:build_resolvers/src/resolver.dart 306:26                                              AnalyzerResolvers._ensureInitialized.<fn>
    package:build_resolvers/src/resolver.dart                                                     AnalyzerResolvers._ensureInitialized.<fn>
    package:build_resolvers/src/resolver.dart 309:6                                               AnalyzerResolvers._ensureInitialized
    package:build_resolvers/src/resolver.dart 314:11                                              AnalyzerResolvers.get
    package:build_runner_core/src/performance_tracking/performance_tracking_resolvers.dart 19:58  PerformanceTrackingResolvers.get.<fn>
    package:build_runner_core/src/generate/performance_tracker.dart 302:15                        _NoOpBuilderActionTracker.trackStage
    package:build_runner_core/src/performance_tracking/performance_tracking_resolvers.dart 19:16  PerformanceTrackingResolvers.get
    package:build                                                                                 BuildStepImpl.resolver
    package:source_gen/src/builder.dart 72:32                                           
    package:build                                                                                 runBuilder
    package:build_runner_core/src/generate/build_impl.dart 485:19                                 _SingleBuild._runForInput.<fn>.<fn>.<fn>
    package:build_runner_core/src/generate/performance_tracker.dart 302:15                        _NoOpBuilderActionTracker.trackStage
    package:build_runner_core/src/generate/build_impl.dart 483:23                                 _SingleBuild._runForInput.<fn>.<fn>
    package:build_runner_core/src/generate/build_impl.dart                                        _SingleBuild._runForInput.<fn>.<fn>
    package:timing/src/timing.dart 222:44                                                         NoOpTimeTracker.track
    package:build_runner_core/src/generate/build_impl.dart 440:22                                 _SingleBuild._runForInput.<fn>
    package:pool/pool.dart 127:28                                                                 Pool.withResource
    package:build_runner_core/src/generate/build_impl.dart 436:17                                 _SingleBuild._runForInput
    package:build_runner_core/src/generate/build_impl.dart 374:38                                 _SingleBuild._runBuilder.<fn>
    dart:async                                                                                    Future.wait
    package:build_runner_core/src/generate/build_impl.dart 373:36                                 _SingleBuild._runBuilder
    package:build_runner_core/src/generate/build_impl.dart 319:20                                 _SingleBuild._runPhases.<fn>.<fn>
    package:build_runner_core/src/generate/build_impl.dart                                        _SingleBuild._runPhases.<fn>.<fn>
    package:build_runner_core/src/generate/performance_tracker.dart 184:15                        _NoOpBuildPerformanceTracker.trackBuildPhase
    package:build_runner_core/src/generate/build_impl.dart 315:47                                 _SingleBuild._runPhases.<fn>
    package:timing/src/timing.dart 222:44                                                         NoOpTimeTracker.track
    package:build_runner_core/src/generate/build_impl.dart 309:32                                 _SingleBuild._runPhases
    package:build_runner_core/src/logging/logging.dart 25:30                                      logTimedAsync
    package:build_runner_core/src/generate/build_impl.dart 266:26                                 _SingleBuild._safeBuild.<fn>
    dart:async                                                                                    runZoned
    package:build_runner_core/src/generate/build_impl.dart 261:5                                  _SingleBuild._safeBuild
    package:build_runner_core/src/generate/build_impl.dart 208:24                       
    package:build_runner_core/src/generate/build_impl.dart 94:56                        
    package:build_runner_core/src/generate/build_runner.dart 25:14                      
    package:args/command_runner.dart 197:27                                                       CommandRunner.runCommand
    package:args/command_runner.dart 112:25                                             <fn>
    dart:async                                                                                    new Future.sync
    package:args/command_runner.dart 112:14                                             
    package:build_runner                                                                          run
    .dart_tool\build\entrypoint\build.dart 27:22                                                  main

    This is the code of "customers_screen_arguments.dart":

    enum CallingAction { Customers1, CustomersOfAdministrator }
    class CustomersScreenArguments {
      final CallingAction callingAction;
      final int administratorCode;
      CustomersScreenArguments(this.callingAction, {this.administratorCode});

    This is the result of "flutter --version:

    Flutter 1.22.3 • channel stable •
    Framework • revision 8874f21e79 (3 days ago) • 2020-10-29 14:14:35 -0700
    Engine • revision a1440ca392
    Tools • Dart 2.10.3

    This is the pubspec.yaml:

    version: 1.0.0+1
      sdk: ">=2.7.0 <3.0.0"
        sdk: flutter
      provider: ^4.0.5
      http: ^0.12.0+2
      shared_preferences: ^0.5.6+3
      json_annotation: ^3.0.0
      material_design_icons_flutter: 4.0.5345
       flutter_icons: ^1.1.0 
      url_launcher: ^5.4.10
      cupertino_icons: ^0.1.2
      package_info: ^0.4.1
        sdk: flutter
      json_serializable: ^3.3.0
      build_runner: ^1.6.7
      sqflite: ^1.3.0
      path: ^1.6.4
      uses-material-design: true
        - assets/collaboration.png
    Thank you.
    State: needs info 
    opened by FabioPagano 27
  • Use the extension methods feature to remove need of most boilerplate

    Use the extension methods feature to remove need of most boilerplate

    Starting with Dart 2.6, json_serializable has the option to create the toJson() method for the user. Although extension methods don't support constructors, json_serializable could create a static generative method instead. This means that user code would look like this:

    import 'package:json_annotation/json_annotation.dart';
    part 'example.g.dart';
    @JsonSerializable(nullable: false)
    class Person {
      final String firstName;
      final String lastName;
      final DateTime dateOfBirth;
      Person({this.firstName, this.lastName, this.dateOfBirth});

    The generated extension might look like this:

    // in example.g.dart
    extension on Person {
      static Person fromJson(Map<String, dynamic> json) => _$PersonFromJson(json);
      Map<String, dynamic> toJson() => _$PersonToJson(this);
    // ...

    Rest of the code can keep the same.

    State: help wanted Type: enhancement 
    opened by filiph 27
  • type '_InternalLinkedHashMap<dynamic, dynamic>' is not a subtype of type 'Map<String, dynamic>' in type cast

    type '_InternalLinkedHashMap' is not a subtype of type 'Map' in type cast

    I get following error, when i want to deserialize an object with a property of type List<> containing another serializeable object. If i change "ChatMember.fromJson(e as Map<String, dynamic>)" to "Map<String, dynamic>.from(e)" everything works perfect. Can you fix this, is there any workaround possible so i can continue my work?

    E/flutter (21470): [ERROR:flutter/shell/common/] Dart Error: Unhandled exception:
    E/flutter (21470): type '_InternalLinkedHashMap<dynamic, dynamic>' is not a subtype of type 'Map<String, dynamic>' in type cast
    E/flutter (21470): #0      Object._as (dart:core/runtime/libobject_patch.dart:78:25)
    E/flutter (21470): #1      _$ChatFromJson.<anonymous closure> (file:///C:/Flutter/src/hapi/lib/datamodels/chat.g.dart:13:56)
    E/flutter (21470): #2      MappedListIterable.elementAt (dart:_internal/iterable.dart:414:29)
    E/flutter (21470): #3      ListIterable.toList (dart:_internal/iterable.dart:219:19)
    E/flutter (21470): #4      _$ChatFromJson (file:///C:/Flutter/src/hapi/lib/datamodels/chat.g.dart:14:13)
    E/flutter (21470): #5      new Chat.fromJson (package:hapi/datamodels/chat.dart:22:55)
    E/flutter (21470): #6      ChatsModel.getChats.<anonymous closure>.<anonymous closure>.<anonymous closure> (package:hapi/models/chats_model.dart:24:72)
    E/flutter (21470): #7      FirestoreHelper.fromListToMap.<anonymous closure> (package:hapi/framework/helper/firestorehelper.dart:8:36)
    E/flutter (21470): #8      MapBase._fillMapWithMappedIterable (dart:collection/maps.dart:67:32)
    E/flutter (21470): #9      new LinkedHashMap.fromIterable (dart:collection/linked_hash_map.dart:124:13)
    E/flutter (21470): #10     FirestoreHelper.fromListToMap (package:hapi/framework/helper/firestorehelper.dart:6:16)
    E/flutter (21470): #11     ChatsModel.getChats.<anonymous closure>.<anonymous closure> (package:hapi/models/chats_model.dart:24:31)
    E/flutter (21470): #12     _RootZone.runUnaryGuarded (dart:async/zone.dart:1314:10)
    E/flutter (21470): #13     _BufferingStreamSubscription._sendData (dart:async/stream_impl.dart:336:11)
    E/flutter (21470): #14     _DelayedData.perform (dart:async/stream_impl.dart:591:14)
    E/flutter (21470): #15     _StreamImplEvents.handleNext (dart:async/stream_impl.dart:707:11)
    E/flutter (21470): #16     _PendingEvents.schedule.<anonymous closure> (dart:async/stream_impl.dart:667:7)
    E/flutter (21470): #17     _microtaskLoop (dart:async/schedule_microtask.dart:41:21)
    E/flutter (21470): #18     _startMicrotaskLoop (dart:async/schedule_microtask.dart:50:5)
    part of 'chat.dart';
    // **************************************************************************
    // JsonSerializableGenerator
    // **************************************************************************
    Chat _$ChatFromJson(Map<String, dynamic> json) {
      return Chat(
          members: (json['members'] as List)
              ?.map((e) =>
                  e == null ? null : ChatMember.fromJson(e as Map<String, dynamic>))
          memberIds: (json['memberIds'] as List)?.map((e) => e as String)?.toList())
        ..creation = json['creation'] == null
            ? null
            : DateTime.parse(json['creation'] as String)
        ..lastUpdate = json['lastUpdate'] == null
            ? null
            : DateTime.parse(json['lastUpdate'] as String);
    Map<String, dynamic> _$ChatToJson(Chat instance) => <String, dynamic>{
          'creation': instance.creation?.toIso8601String(),
          'lastUpdate': instance.lastUpdate?.toIso8601String(),
          'members': instance.members,
          'memberIds': instance.memberIds
    opened by HerrNiklasRaab 27
  • Json_serializable is not generating *.g.dart files

    Json_serializable is not generating *.g.dart files

    Given this class:

    import 'dart:typed_data';
    import 'package:meta/meta.dart';
    import 'package:json_annotation/json_annotation.dart';
    part 'entities.g.dart';
    @JsonSerializable(nullable: false)
    class User {
      final String uid;
      final String email;
      final String displayName;
      final String profilePicture;
      final String accountType;
          {@required this.uid,
          @required this.displayName,
          @required this.profilePicture,
      factory User.fromJson(Map<String, dynamic> json) => _$UserFromJson(json);
      Map<String, dynamic> toJson() => _$UserToJson(this);

    image (Image so you can see what my IDE is highlighting)

    This is inside a dart file called entities.dart image

    This is my pubspec.yaml

    name: <...>
    description: <...>
    version: 1.0.0+1
      sdk: ">=2.6.0 <3.0.0"
        sdk: flutter
      google_sign_in: ^4.4.3
      firebase_auth: ^0.16.0
      firebase_core: ^0.4.4+3
      cloud_firestore: ^0.13.5
      google_fonts: ^1.0.0
      json_annotation: ^3.0.1
      provider: ^4.0.5
      url_launcher: ^5.4.5
      image_picker: ^0.6.5+2
      image_picker_web: ^1.0.6
      string_validator: ^0.1.4
      intl_phone_number_input: ^0.3.0
      currency_pickers: ^1.0.6
      i18n_extension: ^1.3.5
      photo_view: ^0.9.2
      build_runner: ^1.9.0
      json_serializable: ^3.3.0
        sdk: flutter
        sdk: flutter
      uses-material-design: true
        - assets/

    I am running the following command: flutter packages pub run build_runner build

    And this is the console output:

    [INFO] Generating build script...
    [INFO] Generating build script completed, took 384ms
    [INFO] Initializing inputs
    [INFO] Reading cached asset graph...
    [INFO] Reading cached asset graph completed, took 75ms
    [INFO] Checking for updates since last build...
    [INFO] Checking for updates since last build completed, took 741ms
    [INFO] Running build...
    [INFO] Running build completed, took 18ms
    [INFO] Caching finalized dependency graph...
    [INFO] Caching finalized dependency graph completed, took 51ms
    [INFO] Succeeded after 88ms with 0 outputs (0 actions)

    I've tried many variations of the class, it simply wont generate anything.

    I've tried a non-optional constructor, removing @required, changing imports, renaming the dart file, invalidating caches and restarting several times, renaming the class, etc...

    opened by SwissCheese5 26
  • Generate code that supports `implicit-dynamic: false`

    Generate code that supports `implicit-dynamic: false`

    Here's the generated code

    Result _$ResultFromJson(Map<String, dynamic> json) {
      return Result(
        total: json['total'] as String,
        page: json['page'] as int,
        pages: json['pages'] as int,
        tv_shows: (json['tv_shows'] as List)
            ?.map((e) => e == null ? null : Tv.fromJson(e as Map<String, dynamic>))

    And here's the error.

     error • Missing parameter type for 'e' at lib/demo.g.dart:15:16 • implicit_dynamic_parameter


    Type: enhancement State: blocked P2 medium 
    opened by trevorwang 26
  • support for nested items in @JsonKey(name:)

    support for nested items in @JsonKey(name:)

    It would be great if we could directly access nested items in the name String of @JsonKey. Consider this Json:

    "root_item": {
        "items": [
                "name": "first nested item"
                "name": "second nested item"

    I would like to do:

    @JsonKey(name: "root_item/items")
    List<NestedItem> nestedItems;

    Sorry if this is already possible, but i could not find anything.

    State: help wanted Type: enhancement P2 medium 
    opened by KorbinianMossandl 26
  • Add support for nested field names

    Add support for nested field names

    Hi I added support for accessing nested field directly. and I included different examples and all the tests are passed, Please check it I don't know i miss something.


    opened by rebaz94 20
  • Add casting support

    Add casting support

    I've integrated with a very bad API. Their JSON didn't have any types, it was all strings. It would be very usefull to have something like this:

      "ugly": "true",
    class Example {
        name: 'ugly',
        fromJson: (v) => v == 'true',
        toJson: (v) => v.toString(),
      final bool pretty;
    Type: enhancement 
    opened by ianldgs 20
  • Generic argument factories does not work with toJson when using mixin

    Generic argument factories does not work with toJson when using mixin

    The following file throws in the generator (probably because it tries to compare the type Child<T> with ChildMixin<T>). I also reported this at but perhaps it's something that can be fixed in json_serializable.

    If I move the toJson method to the Child class, it works fine.

    build_runner build -v

    [SEVERE] json_serializable on lib/src/bug.dart:
    RangeError (index): Invalid value: Only valid value is 0: -1
    dart:core                                                           List.[]
    package:json_serializable/src/type_helpers/json_helper.dart 158:39  _helperParams
    package:json_serializable/src/type_helpers/json_helper.dart 51:9    JsonHelper.serialize
    package:json_serializable/src/type_helper_ctx.dart 56:31            TypeHelperCtx.serialize.<fn>
    dart:core                                                           Iterable.firstWhere
    package:json_serializable/src/type_helper_ctx.dart 88:46            TypeHelperCtx._run
    package:json_serializable/src/type_helper_ctx.dart 53:64            TypeHelperCtx.serialize
    package:json_serializable/src/encoder_helper.dart 153:12            EncodeHelper._serializeField
    package:json_serializable/src/encoder_helper.dart 81:42             EncodeHelper._writeToJsonSimple.<fn>
    dart:core                                                           StringBuffer.writeAll
    package:json_serializable/src/encoder_helper.dart 78:9              EncodeHelper._writeToJsonSimple
    package:json_serializable/src/encoder_helper.dart 66:7              EncodeHelper.createToJson
    dart:_internal                                                      WhereIterator.moveNext
    package:json_serializable/src/json_part_builder.dart 64:27          _UnifiedGenerator.generate
    package:source_gen/src/builder.dart 352:23                          _generate


      sdk: '>=2.18.1 <3.0.0'
      build_runner: ^2.2.1
      json_serializable: ^6.4.0
      json_annotation: ^4.7.0


    import 'package:json_annotation/json_annotation.dart';
    part 'bug.g.dart';
    class Person {
      final Child<String> firstName;
      Person({required this.firstName});
      factory Person.fromJson(Map<String, dynamic> json) => _$PersonFromJson(json);
      Map<String, dynamic> toJson() => _$PersonToJson(this);
    @JsonSerializable(genericArgumentFactories: true)
    class Child<T> with ChildMixin<T> {
      final T content;
      Child({required this.content});
      factory Child.fromJson(
              Map<String, dynamic> json, T Function(Object? json) fromJsonT) =>
          _$ChildFromJson<T>(json, fromJsonT);
    mixin ChildMixin<T> {
      Map<String, dynamic> toJson(Object Function(T) toJsonT) =>
          _$ChildToJson(this, toJsonT);
    State: help wanted Type: bug P3 low 
    opened by norpan 3
  • Arg `includeIfNull` is ignored when type is not nullable

    Arg `includeIfNull` is ignored when type is not nullable

    Flutter Version
    Flutter 3.3.2 • channel stable •
    Framework • revision e3c29ec00c (6 days ago) • 2022-09-14 08:46:55 -0500
    Engine • revision a4ff2c53d8
    Tools • Dart 2.18.1 • DevTools 2.15.0

    In my case, I have an enum with a null json value (to avoid a nullable type within my model class)

    enum BrandedType {

    My Dart model class property:

    @JsonKey(includeIfNull: false)
    final BrandedType brandedType;

    This is the generated code for this property

    'branded_type': _$BrandedTypeEnumMap[instance.brandedType]!,
    const _$BrandedTypeEnumMap = { 1, 2,
      BrandedType.unknown: null,

    And this is the json output for this property

    "branded_type": null

    What's happening in the generator is it's checking for a nullable type on the model class's property type. If the property is not a nullable type (as a Dart object), then it would seem redundant to generate the writeNotNull method because the value appears to not be nullable (as a serialized object).

    This can be validated by making the property's type nullable

    // --- model ---
    @JsonKey(includeIfNull: false)
    final BrandedType? brandedType;
    // --- generated code ---
    void writeNotNull(String key, dynamic value) {
        if (value != null) {
          val[key] = value;
    writeNotNull('branded_type', _$BrandedTypeEnumMap[instance.brandedType]);
    const _$BrandedTypeEnumMap = { 1, 2,
      BrandedType.unknown: null,

    Even when the dart object's value is set to BrandedType.unknown, there is no json output for this property when resolved with the _$BrandedTypeEnumMap value, because it resolves to null.

    There is another possible outcome, instead of _$EnumMap[...] (where the key's value could return a null value), it would be property.toJson() (where toJson could return a null value). Since we are checking for the null value against the serialized property, and not the Dart model object's current value, the property's type isn't relevant.

    A possible fix for this would be to ignore the nullable typing on the property of the Dart object, and generate the writeNotNull regardless.

    opened by mrgnhnt96 0
  • Invalid code generated for `checked: true` when `json_annotation` is imported with a prefix

    Invalid code generated for `checked: true` when `json_annotation` is imported with a prefix

    I encountered some incorrect code generation when setting checked: true and importing json_annotation with a prefix:

    import 'package:json_annotation/json_annotation.dart' as _i1;
    part 'my_class.g.dart';
    @_i1.JsonSerializable(checked: true)
    class MyClass {
      final String field1;
      final String field2;
        required this.field1,
        required this.field2,
      factory MyClass.fromJson(Map<String, dynamic> json) =>

    The generated code attempts to use the unqualified $checkedCreate instead of _i1.$checkedCreate:

    part of 'my_class.dart';
    // **************************************************************************
    // JsonSerializableGenerator
    // **************************************************************************
    MyClass _$MyClassFromJson(Map<String, dynamic> json) => $checkedCreate(
          ($checkedConvert) {
            final val = MyClass(
              field1: $checkedConvert('field1', (v) => v as String),
              field2: $checkedConvert('field2', (v) => v as String),
            return val;
    Map<String, dynamic> _$MyClassToJson(MyClass instance) => <String, dynamic>{
          'field1': instance.field1,
          'field2': instance.field2,

    This results in an error in the generated code:

    The function '$checkedCreate' isn't defined.
    State: help wanted Type: enhancement P2 medium pkg:json_serializable 
    opened by jjoelson 1
  • [request] Generate utilities to serialize only a specific property of an object

    [request] Generate utilities to serialize only a specific property of an object

    Hello! I'm bothering you one more time for some cloud_firestore_odm issues 🙈


    Long story short, I'm trying to fix The gist of the issue is that the ODM wants to partially encode an object.

    So for:

    class Person {
      final String firstName;
      final String lastName;

    someone may want to update only the lastName property of Person. In plain Firestore, that would be:

    personCollection.doc('42').update({'last_name': 'Mona'});

    With the ODM, this ends-us as:

    personCollection.doc('42').update(lastName: 'Mona');
    // generate source code for update
    class PersonDocumentReference {
      Future<void> update({String lastName = _sentinel}) {
        return _reference.upate({
          if (lastName != _sentinel)
            _$PersonFieldMap['lastName']!: lastName as String,

    That works for simple primitives like String. But for anything more complex, this doesn't work anymore.

    For that, what I would need would be to invoke the "toJson" of Person, but only for its lastName property.


    My thought for solving this would be to do something similar to what was done with "XFieldMap", but for a "toJson" variant

    For example, for:

    class Complex {
      final MyEnum enum;
      final Person person;
    enum MyEnum {
    class Person {
      final String firstName;
      final String lastName;

    we could generate the following utility for Complex:

    abstract class _$ComplexPropertyPerFieldToJson {
      static Map<String, Object?> person(Person person) {
        return person.toJson();
      static String enum(MyEnum enum) {
        switch (enum) {
          case MyEnum.a: return 'hello_world';

    This would allow the Firestore ODM to generate:

    class ComplexDocumentReference {
      Future<void> update({MyEnum enum = _sentinel, Person person = _sentinel}) {
        return _reference.upate({
          if (enum != _sentinel)
            _$ComplexFieldMap['enum']!: _$ComplexPropertyToJson.enumToJson(enum as MyEnum),
          if (person != _sentinel)
            _$ComplexFieldMap['person']!: _$ComplexPropertyToJson.personToJson(person as Person),
    opened by rrousselGit 0
  • [Feature Request] Ignore unknown enum values in list

    [Feature Request] Ignore unknown enum values in list

    Currently, it seems not to be possible to ignore unknown enum values when serializing.

    Given the following example:

    enum MyEnum {
     a, b, c
    class MyModel {
      List<MyEnum> enums;

    This will fail for the input {"enums": ["a", "b", "d"]}.

    What would be great to see is making this possible:

    class MyModel {
      @JsonKey(ignoreUnknownEnums: true)
      List<MyEnum> enums;

    which won't fail with the given input but create an object MyModel(enums: [MyEnum.a, MyEnum.b]).

    For the generated code something like this should work:

    enums: (json['enums'] as List<dynamic>?)
                  ?.map((e) => $enumDecodeNullable(_$DogSleepingPlaceEnumMap, e)).whereNotNull()
    Type: enhancement pkg:json_serializable pkg:json_annotation 
    opened by stefangaller 0
  • Add an option to create the reversed enum map

    Add an option to create the reversed enum map

    It would be very useful to create a reversed enum map:

    enum MyEnum {

    What is currently generated:

    const _$MobileScreenNameEnumMap = {
      MyEnum.a: 'a',
      MyEnum.b: 'b',

    It would be very useful to generate:

    const _$MobileScreenNameEnumMapFromNames = { // Or whatever better name.
      'a': MyEnum.a,
      'b': MyEnum.b,

    With maybe some assertions when generating that check the json keys are all unique

    opened by ValentinVignal 0
Google ❤️ Open Source
Okan YILDIRIM 37 Jul 10, 2022
Material color utilities

Material color utilities Algorithms and utilities that power the Material Design 3 (M3) color system, including choosing theme colors from images and

null 683 Sep 23, 2022
Utilities to make working with 'Duration's easier.

duration Utilities to make working with 'Duration's easier. NOTE: Use prettyDuration, prettySeconds, prettyMilliseconds instead of printDuration, prin

null 45 Sep 21, 2022
Converts SVG icons to OTF font and generates Flutter-compatible class. Provides an API and a CLI tool.

Fontify The Fontify package provides an easy way to convert SVG icons to OpenType font and generate Flutter-compatible class that contains identifiers

Igor Kharakhordin 86 Sep 21, 2022
A library for Dart that generates fake data

faker A library for Dart that generates fake data. faker is heavily inspired by the Python package faker, and the Ruby package ffaker. Usage A simple

Jesper Håkansson 185 Sep 22, 2022
A builder that generates an ArgsParser from a class

Parse command line arguments directly into an annotation class using the Dart Build System. Example Annotate a class with @CliOptions() from package:b

Kevin Moore 41 Sep 8, 2022
A CLI tool to help generate dart classes from json returned from API

Json 2 Dart Command line utility Important note There is already a package called json2dart so this package will be called json2dartc ! This project w

Adib Mohsin 39 May 23, 2022
An auto mapper for Dart. It allows mapping objects of different classes automatically and manually using JSON serialization.

AutoMapper for Dart An auto mapper for Dart. It allows mapping objects of different classes automatically and manually using JSON serialization. Examp

Leynier Gutiérrez González 7 Aug 24, 2022
A generator to create config class from json files that support many environments

A generator to create config class from json files that support many environments. Motivation If you use a json file to config your applications, perp

Diego Cardenas 0 Oct 9, 2021
A flutter package that allows you to transform your excel to json

excel_to_json A package that allows you to transform your excel to the following format: Excel To JSON Getting Started At current the package allows y

Vitor Amaral de Melo 0 Apr 5, 2022
JSON API parser for Flutter

Flutter Japx - JSON:API Decoder/Encoder Lightweight [JSON:API][1] parser that flattens complex [JSON:API][1] structure and turns it into simple JSON a

Infinum 22 May 4, 2022
library to help you create database on local memory, support json local database inspired by lowdb

Licensed Licensed under the MIT License <>. SPDX-License-Identifier: MIT Copyright (c) 2021 Azkadev <http://github.c

Azka Full Snack Developer:) 35 Feb 11, 2022
A flutter application , that create dynamic forms from json data

checktyper A new Flutter project. Getting Started This project is a starting point for a Flutter application. A few resources to get you started if th

DotCoder 1 Aug 23, 2022
Cache json map to local file with Dart:io. Read file with sync api.

local_cache_sync 一个非常简单易用的Flutter本地储存库,适用于在本地储存一列轻量数据(例如用户保存在本地的设备信息,或者缓存一系列用户信息)。 local_cache_sync的所有方法都是同步,而不是异步的。这意味着你不需要使用await就可以获取数据。在flutter中,这

null 16 Jun 24, 2022
From JSON to Dart Advanced

From JSON to Dart Advanced Table of Contents Features Convert from clipboard Convert from selection Convert from clipboard to code generation Convert

 нιяαитнα 71 Aug 29, 2022
Args simple - A simple argument parser and handler, integrated with JSON and dart

args_simple A simple argument parser and handler, integrated with JSON and dart:

Graciliano Monteiro Passos 1 Jan 22, 2022
This package allows programmers to annotate Dart objects in order to Serialize / Deserialize them to / from JSON

This package allows programmers to annotate Dart objects in order to Serialize / Deserialize them to / from JSON. Why? Compatible with all target plat

Alexander Mazuruk 344 Sep 12, 2022
🎯 This library automatically generates object classes from JSON files that can be parsed by the freezed library.

The Most Powerful Way to Automatically Generate Model Objects from JSON Files ⚡ 1. Guide ?? 1.1. Features ?? 1.1.1. From 1.1.2. To 1.2. Getting Starte

KATO, Shinya / 加藤 真也 12 Aug 28, 2022
Provides null-safety implementation to simplify JSON data handling by adding extension method to JSON object

Lazy JSON Provides null-safety implementation to simplify JSON data handling by adding extension method to JSON object and JSON array. Getting started

Kinnara Digital Studio 0 Oct 27, 2021
Flutter package: Json Table Widget to create table from json array

Json Table Widget ?? Proudly Sponsored by FieldAssist Request a Demo This Flutter package provides a Json Table Widget for directly showing table from

Ayush P Gupta 188 Sep 6, 2022