标签: json-serializable

Freezed 和 json_serialized:如何使用自定义转换器

我想将自定义转换器添加到冻结的类中,就像这个答案一样。

我用这段代码尝试过:

@freezed
class NewsPost with _$NewsPost {
  factory NewsPost({
    @JsonKey(name: "date") @TimestampConverter() DateTime? date,
  }) = _NewsPost;

  factory NewsPost.fromJson(Map<String, dynamic> json) =>
      _$NewsPostFromJson(json);
}
Run Code Online (Sandbox Code Playgroud)

但这没有用。任何想法都非常受欢迎!

为了您的兴趣,这是我的转换器:

class TimestampConverter implements JsonConverter<DateTime, Timestamp> {
  const TimestampConverter();

  @override
  DateTime fromJson(Timestamp timestamp) {
    return timestamp.toDate();
  }

  @override
  Timestamp toJson(DateTime date) => Timestamp.fromDate(date);
}
Run Code Online (Sandbox Code Playgroud)

谢谢 :-)

flutter json-serializable freezed

33
推荐指数
2
解决办法
2万
查看次数

Flutter:json_serialized 忽略可为 null 的字段而不是抛出错误

假设有两个模型UserCity

@JsonSerializable()
class User {
    int id;
    String name;
    City? city;
    List<Map<String, City>>? listMapCity;

}

@JsonSerializable()
class City {
   int id;
   String name;
}
Run Code Online (Sandbox Code Playgroud)

现在假设在 API 调用期间,我们有一个用户模型,但在城市对象模型中,我们只得到id而不是name。像这样的东西

{
    "id": 5,
    "name": "Matthew",
    "city": {
        "id": 12
    }
}
Run Code Online (Sandbox Code Playgroud)

但由于 json_serialized 和 json_annotation 的默认性质。该 JSON 未映射到 User 模型,在映射期间,它会抛出异常。
Null 类型不是 String 类型的子类型。(因为这里城市对象中缺少名称键)

但正如我们已经在 User 对象中声明的 City 是可选的,我希望它应该解析 User JSON,其中citylistMapCity为 null。

任何帮助或解决方案将不胜感激,谢谢

dart flutter json-serializable dart-null-safety

11
推荐指数
2
解决办法
9896
查看次数

Flutter json_serialized 如果 key 可以有不同的名称怎么办

我在 Flutter 中使用 json_serialized 将类存储在文件中并从中读回。为了简单起见,我不会在这里发布原始类,但原则是在编写应用程序的一半过程中,我决定将变量名称“aStupidName”更改为“name”。我如何建议代码生成实用程序将带有键“aStupidName”的 JSON 值(如果 JSON 中存在)分配给变量“name”,但如果存在键“name”,则将其分配给变量,即在文件的较新版本中?

flutter json-serializable

9
推荐指数
1
解决办法
7298
查看次数

对 isar 数据库和 JsonSerialized 使用单个 Flutter 模型

我尝试使用单一模型来使用 Isar 在本地存储数据,并与 Retrofit 一起使用来处理 REST API 请求。

\n

Isar要求所有链接类都使用数据类型进行定义,IsarLink<MyClassName>JsonSerialized则要求使用它们MyClassName作为数据类型。

\n
@Collection()\n@JsonSerializable()\nclass UserGroup {\n  @JsonKey(ignore: true)\n  Id localId = Isar.autoIncrement; // you can also use id = null to auto increment\n\n  @ignore\n  @JsonKey(name: "_id")\n  String? id;\n\n  String name;\n  String description;\n\n  @ignore\n  Domain? domain;\n  \n  @ignore\n  UserGroupPermissions permissions;\n\n  @ignore\n  Organization? organization;\n\n  \n  @JsonKey(ignore: true)\n  IsarLink<Organization?> organization = IsarLink<Organization?>();\n\n  UserGroup({\n    this.id,\n    required this.name,\n    required this.description,\n    this.domain,\n    required this.permissions,\n    this.organization,\n  });\n\n  factory UserGroup.fromJson(Map<String, dynamic> json) …
Run Code Online (Sandbox Code Playgroud)

model retrofit flutter json-serializable flutter-isar

8
推荐指数
1
解决办法
2677
查看次数

具有枚举属性的冻结类在尝试序列化时会引发错误

我有一个冻结的类,它在其构造函数中采用枚举,但是当尝试在此类上执行 jsonEncode 方法时,它失败并出现以下错误:

处理手势时抛出以下 JsonUnsupportedObjectError:将对象转换为可编码对象失败:“InputType”实例

我已用 JsonValue("...") 注释了我的枚举案例,但我没有看到任何为枚举生成的代码。

这是一个错误还是我做错了什么?

完整示例如下:

@freezed
class Input with _$Input {
  const factory Input({
    @Default(0) int seconds,
    @Default(0) double bolus,
    @Default(0) double infusion,
    @Default(InputType.Bolus) currentInputType,
  }) = _Input;

  factory Input.fromJson(Map<String, dynamic> json) => _$InputFromJson(json);
}

enum InputType {
  @JsonValue("bolus")
  Bolus,
  @JsonValue("infusion")
  Infusion,
}

// When calling jsonEncode(someInput); throws the specified error.

Update: freezed needs the enum type specified in the factory constructor! Default value is not enough.
Run Code Online (Sandbox Code Playgroud)

enums flutter json-serializable freezed flutter-freezed

7
推荐指数
1
解决办法
6704
查看次数

Flutter Freezed 模型升级后 JsonSerialized 和 JsonKey 问题

我的应用程序运行正常,但在 pub Upgrade --major-versions 之后,我在所有型号上都遇到问题。型号示例:

import 'package:app_220/models/Leads/LeadFieldModel.dart';
import 'package:flutter/foundation.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
import 'package:intl/intl.dart';

part 'LeadModel.freezed.dart';
part 'LeadModel.g.dart';

@freezed
abstract class LeadModel with _$LeadModel {
  const LeadModel._();

  @JsonSerializable(fieldRename: FieldRename.snake)
  const factory LeadModel({
    required int id,
    int? formId,
    @JsonKey(name: 'contact__first_name', defaultValue: '')
    @Default('')
        String contactFirstName,
    @JsonKey(name: 'contact__last_name', defaultValue: '')
    @Default('')
        String contactLastName,
    @JsonKey(name: 'contact__email', defaultValue: '')
    @Default('')
        String contactEmail,
    @JsonKey(name: 'contact__phone', defaultValue: '')
    @Default('')
        String contactPhone,
    int? staffId,
    @Default('') String staffLastName,
    DateTime? creationTime,
    @Default('') String sourceUrl,
    @Default('') String sourceIp,
    @Default(0) int viewed, …
Run Code Online (Sandbox Code Playgroud)

flutter json-serializable freezed json-annotation

7
推荐指数
1
解决办法
7494
查看次数

如何正确构建.yaml?

我刚刚开始学习Flutter。我使用 vscode 作为编辑器

我需要在我的代码中使用 json_serialized 。我阅读了https://pub.dev/packages/json_serialized并使我的 build.yaml 就像那里显示的那样。

targets:
  $default:
    builders:
      json_serializable:
        options:
          # Options configure how source code is generated for every
          # `@JsonSerializable`-annotated class in the package.
          #
          # The default value for each is listed.
          any_map: false
          checked: false
          constructor: ""
          create_factory: true
          create_to_json: true
          disallow_unrecognized_keys: false
          explicit_to_json: false
          field_rename: none
          generic_argument_factories: false
          ignore_unannotated: false
          include_if_null: true
Run Code Online (Sandbox Code Playgroud)

但 vscode 说:不允许使用属性目标。yaml-schema:Hammerkit YAML 架构 [1,1]

仅供参考,这是我的 pubspec.lock

# Generated by pub
# See https://dart.dev/tools/pub/glossary#lockfile
packages:
  _fe_analyzer_shared:
    dependency: …
Run Code Online (Sandbox Code Playgroud)

flutter json-serializable

7
推荐指数
1
解决办法
3075
查看次数

如何在 json_serialized 中使用私有构造函数

我在类中使用私有构造函数,但代码生成失败

该类Foo没有默认构造函数。

我正在使用最新json_serializable: 版本,即6.1.5

@JsonSerializable()
class Foo {
  final int count;
  Foo._(this.count);

  factory Foo.fromJson(Map<String, dynamic> json) => _$Foo._FromJson(json);
}
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

dart flutter json-serializable

7
推荐指数
1
解决办法
1092
查看次数

`未处理的异常:无效参数:'_$_Category'的实例`将数据发送到 firestore 形成冻结的生成类时

我用 freeze 创建了两个模型类。一个类内部有其他类的参数。当我尝试将数据发送到 firestore 时,问题开始了。出现以下错误。

\n
E/flutter ( 6175): [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: Invalid argument: Instance of \'_$_Category\'\nE/flutter ( 6175): #0      convertPlatformException\npackage:cloud_firestore_platform_interface/\xe2\x80\xa6/utils/exception.dart:14\nE/flutter ( 6175): #1      MethodChannelDocumentReference.set\npackage:cloud_firestore_platform_interface/\xe2\x80\xa6/method_channel/method_channel_document_reference.dart:44\nE/flutter ( 6175): <asynchronous suspension>\nE/flutter ( 6175): #2      _JsonCollectionReference.add\npackage:cloud_firestore/src/collection_reference.dart:109\nE/flutter ( 6175): <asynchronous suspension>\nE/flutter ( 6175): #3      _WithConverterCollectionReference.add\npackage:cloud_firestore/src/collection_reference.dart:180\nE/flutter ( 6175): <asynchronous suspension>\nE/flutter ( 6175): #4      _HomeScreenState.product\npackage:mr_grocery/home/home_screen.dart:45\nE/flutter ( 6175): <asynchronous suspension>\n
Run Code Online (Sandbox Code Playgroud)\n

模型类

\n
    \n
  1. 产品(具有类别类参数)
  2. \n
\n
\n@freezed\nclass Product with _$Product {\n  const factory Product({\n    required int amount,\n    required List<Category> categories, // Category class generated by freezed\n …
Run Code Online (Sandbox Code Playgroud)

dart flutter google-cloud-firestore json-serializable freezed

6
推荐指数
1
解决办法
4955
查看次数

使用 dart json_serialized 将对象字段映射到 JSON 平面键(一对多映射)

我有一个 dart 对象,其中包含一个类型为 的字段,该字段本身由和Money组成:amountcurrency

@JsonSerializable()
class Account {

  final String id;
  final String type;
  final String subtype;
  final String origin;
  final String name;
  final String status;
  final String currency;
  final Money balance; <== value object
  ...
}
Run Code Online (Sandbox Code Playgroud)

Money看起来像这样:

class Money {
  final int amount;
  final String currency;

  const Money(this.amount, this.currency);
  ...
}
Run Code Online (Sandbox Code Playgroud)

上面的内容将被映射以供使用sqflite,因此目标 JSON 必须是平面 JSON,例如:

{
  "id": String,
  "type": String,
  "subtype": String,
  "origin": String,
  "name": String,
  "status": String,
  "currency": String,
  "balanceAmount": int; …
Run Code Online (Sandbox Code Playgroud)

dart json-serializable

6
推荐指数
1
解决办法
1930
查看次数