json_serializable.dart icon indicating copy to clipboard operation
json_serializable.dart copied to clipboard

No code generated when using modified fromJson factory

Open kuchienkz opened this issue 7 months ago • 1 comments

Since there is a need to convert older version data model (which saved locally), I customized the fromJson factory as follows:

import 'package:json_annotation/json_annotation.dart';

part 'user.g.dart';

@JsonSerializable(nullable: false)
class User {
  // final String firstName;  //deprecated
  // final String lastName; //deprecated
  final String fullname;

  User({this.fullname});

  factory User.fromJson(Map<String, dynamic> json) {
      if (json.containsKey('firstName') {
          json['fullname'] = json['firstName'] + " " + json['lastName'];
          json.remove('firstName');
          json.remove('lastName');
      }

     return  _$UserFromJson(json);
  }

  Map<String, dynamic> toJson() => _$UserToJson(this);
}

With the above code, build_runner does not generate the *.g.dart file. But when I changed the fromJson like the usual:

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

...the *.g.dart file is generated.

Im quite new with flutter/dart but I think the custom fromJson should have work. Did I miss something?

Also, what I've tried: Running with clean first, did not work. Running with --verbose does give any error message.

kuchienkz avatar Sep 22 '25 23:09 kuchienkz

@kuchienkz See comment here: https://pub.dev/packages/freezed#fromjsontojson, you have to use => only for fromJson since the new version of Freezed

dsvishchov avatar Oct 23 '25 10:10 dsvishchov