build_runner is not generating correct toJson methods

Issue

test.dart file:

import 'package:json_annotation/json_annotation.dart';

import 'foo.dart';

part 'test.g.dart';

@JsonSerializable()
class Test {
  Test(this.foo);

  factory Test.fromJson(Map<String, dynamic> json) => _$TestFromJson(json);
  Map<String, dynamic> toJson() => _$TestToJson(this);

  final Foo? foo;
}

test.g.dart class

// GENERATED CODE - DO NOT MODIFY BY HAND

part of 'test.dart';

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

Test _$TestFromJson(Map<String, dynamic> json) {
  return Test(
    json['foo'] == null
        ? null
        : Foo.fromJson(json['foo'] as Map<String, dynamic>),
  );
}

Map<String, dynamic> _$TestToJson(Test instance) => <String, dynamic>{
      'foo': instance.foo,
    };

Months ago the classes were generated with another _$TestToJson. Every custom class field where like this:

'foo': instance.foo?.toJson(),

now the ?.toJson() is missing. The result is a Map with objects from custom classes. But i need a tree with maps of maps of maps ….. Because when I try to use the fromJson, the tree is not correct for reconverting.

Here is the foo.dart

import 'package:json_annotation/json_annotation.dart';

part 'foo.g.dart';

@JsonSerializable()
class Foo {
  Foo();

  factory Foo.fromJson(Map<String, dynamic> json) => _$FooFromJson(json);
  Map<String, dynamic> toJson() => _$FooToJson(this);
}
 

Solution

The build.yaml was missing.

Here here is my build.yaml

targets:
  $default:
    builders:
      json_serializable:
        options:
          explicit_to_json: true

explicit_to_json is by default false

Answered By – Raegtime

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published