如何生成带有扩展类的 JsonSerialized

问题描述 投票:0回答:1

我正在干净的架构中创建一个产品应用程序,我想生成json,但我无法使用 JsonSerialized 来做到这一点,但我无法做到这一点,我总是收到错误

Could not generate `fromJson` code for `categories` because of type `CategoryEntity`.
package:mermate/features/products/domain/entities/product_entity.dart:6:30
  ╷
6 │   final List<CategoryEntity> categories;
  │                              ^^^^^^^^^^

我试过了,

域/product_entity.dart

class ProductEntity extends Equatable {
  final int id;
  final List<CategoryEntity> categories;

  const ProductEntity({required this.id, required this.categories});

  @override
  List<Object> get props => [id, categories];
}

class CategoryEntity extends Equatable {
  final int id;

  const CategoryEntity({required this.id});

  @override
  List<Object> get props => [id];
}

数据/product_model.dart

import 'package:freezed_annotation/freezed_annotation.dart';
import 'package:mermate/features/products/domain/entities/product_entity.dart';
part 'product_model.g.dart';

@JsonSerializable(explicitToJson: true)
class ProductModel extends ProductEntity {
  const ProductModel({required super.id, required super.categories});
  factory ProductModel.fromJson(Map<String, dynamic> json) =>
      _$ProductModelFromJson(json);
  Map<String, dynamic> toJson() => _$ProductModelToJson(this);
}

@JsonSerializable()
class CategoryModel extends CategoryEntity {
  const CategoryModel({required super.id});
  factory CategoryModel.fromJson(Map<String, dynamic> json) =>
      _$CategoryModelFromJson(json);
  Map<String, dynamic> toJson() => _$CategoryModelToJson(this);
}
flutter dart jsonserializer json-serialization
1个回答
0
投票

试试这个方法,更干净,而且你甚至不需要

JsonSerializable

1- ProductEntity 类:

class ProductEntity extends Equatable {
  final int id;
  final List<CategoryEntity> categories;

  const ProductEntity({
    required this.id,
    required this.categories
  });

  @override
  List<Object> get props => [id, categories];

  static ProductEntity fromJson(
    Map<String, dynamic> json,
  ) {
    return ProductEntity(
      id: json['id'],
      categories: CategoryEntity.fromJsonList(json['categories']),
    );
  }
}

2- CategoryEntity 类:

class CategoryEntity extends Equatable {
  final int id;

  const CategoryEntity({
    required this.id
  });

  @override
  List<Object> get props => [id];

  static CategoryEntity fromJson(
    Map<String, dynamic> json,
  ) {
    return CategoryEntity(
      id: json['id'],
    );
  }

  static List<CategoryEntity> fromJsonList(
    List<dynamic> jsonList,
  ) {
    if (jsonList == null) {
      return null;
    }
    return jsonList
        .map<CategoryEntity>(
          (
            dynamic jsonObject,
          ) =>
              CategoryEntity.fromJson(
            jsonObject,
          ),
        )
        .toList();
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.