我想将自定义转换器添加到冻结的类中,就像这个答案一样。
我用这段代码尝试过:
@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)
谢谢 :-)
假设有两个模型User和City
@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,其中city和listMapCity为 null。
任何帮助或解决方案将不胜感激,谢谢
我在 Flutter 中使用 json_serialized 将类存储在文件中并从中读回。为了简单起见,我不会在这里发布原始类,但原则是在编写应用程序的一半过程中,我决定将变量名称“aStupidName”更改为“name”。我如何建议代码生成实用程序将带有键“aStupidName”的 JSON 值(如果 JSON 中存在)分配给变量“name”,但如果存在键“name”,则将其分配给变量,即在文件的较新版本中?
我尝试使用单一模型来使用 Isar 在本地存储数据,并与 Retrofit 一起使用来处理 REST API 请求。
\n但Isar要求所有链接类都使用数据类型进行定义,IsarLink<MyClassName>而JsonSerialized则要求使用它们MyClassName作为数据类型。
@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) 我有一个冻结的类,它在其构造函数中采用枚举,但是当尝试在此类上执行 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) 我的应用程序运行正常,但在 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。我使用 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) 我在类中使用私有构造函数,但代码生成失败
该类
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)
我究竟做错了什么?
我用 freeze 创建了两个模型类。一个类内部有其他类的参数。当我尝试将数据发送到 firestore 时,问题开始了。出现以下错误。
\nE/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>\nRun Code Online (Sandbox Code Playgroud)\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
我有一个 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)