把这个问题贴出来自己回答。希望这能帮上忙。
的问题:生成的代码与颤振freezed
,但更改到和从json字段名到一个特定的重命名模式。
发布于 2022-08-23 12:59:53
解决方案:
build.yaml
假设您有一个用freezed
编写的类,如下所示
import 'package:freezed_annotation/freezed_annotation.dart';
import 'dart:convert';
part 'my_calss.freezed.dart';
part 'my_calss.g.dart';
@freezed
abstract class MyCalss with _$MyCalss {
const factory MyCalss({
@required int field1,
@required String field2,
}) = _MyCalss;
factory MyCalss.fromJson(Map<String, dynamic> json) => _$MyCalssFromJson(json);
}
若要更改my_calss.g.dart
类以使用例如pascal
大小写,请执行以下操作:
将以下内容放入您的build.yaml
# targets:
# $default:
# builders:
# freezed:
# options:
# union_key: type
# union_value_case: pascal
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_field_map: false
create_to_json: true
disallow_unrecognized_keys: false
explicit_to_json: false
field_rename: pascal
generic_argument_factories: false
ignore_unannotated: false
include_if_null: true
感兴趣的主要领域是field_rename
,它可以是下面列出的json_serializable
中枚举FieldRename
的任意值。
/// Values for the automatic field renaming behavior for [JsonSerializable].
enum FieldRename {
/// Use the field name without changes.
none,
/// Encodes a field named `kebabCase` with a JSON key `kebab-case`.
kebab,
/// Encodes a field named `snakeCase` with a JSON key `snake_case`.
snake,
/// Encodes a field named `pascalCase` with a JSON key `PascalCase`.
pascal,
/// Encodes a field named `screamingSnakeCase` with a JSON key
/// `SCREAMING_SNAKE_CASE`
screamingSnake,
}
最初,我发现了这个github页面这里,它说要执行以下操作
However, when I write this, there is an error (when I checked the generated file, it was generated twice)
@freezed
@JsonSerializable(fieldRename: FieldRename.snake)
class Example with _$Example {
factory Example() = GeneratedClass;
}
So rewriting it this way works fine.
@freezed
class Example with _$Example {
@JsonSerializable(fieldRename: FieldRename.snake)
factory Example() = GeneratedClass;
}
这两种解决方案都没有帮助我,只是编辑build.yaml
文件解决了问题。
我正在使用的版本
#Freezed
freezed_annotation: ^2.1.0
#json annotations
json_annotation: ^4.6.0
dev_dependencies:
flutter_test:
sdk: flutter
build_runner: ^2.2.0
flutter_lints: ^2.0.1
freezed: ^2.1.0+1
json_serializable: ^6.3.1
https://stackoverflow.com/questions/73459180
复制相似问题