【发布时间】:2022-08-10 14:14:28
【问题描述】:
我正在尝试从文件中解析一些 JSON,并决定使用 Freezed 来生成代码。问题是(据我所知)没有办法使用 JSON 对象的名称。
所以说我有以下 JSON 对象:
{
\"uniqueName\":{
\"website\": \"https://www.example.com/\",
\"description\": \"Some description\",
\"hosted_demo\": false,
\"demo\": \"\",
\"oss\": false,
\"source\": \"\",
\"other-links\": [
{
\"title\": \"Clients\",
\"site\": \"https://shlink.io/apps\"
}
],
\"license\": \"MIT\"
}
}
那么这将是 Freezed 代码 (done with instructions from this site) 所需的 dart 代码:
// 1. import freezed_annotation
import \'package:freezed_annotation/freezed_annotation.dart\';
// import any other models we depend on
import \'otherLinks.dart\';
// 2. add \'part\' files
part \'freezed_files/item.freezed.dart\';
part \'generated/item.g.dart\';
// 3. add @freezed annotation
@freezed
// 4. define a class with a mixin
class Item with _$Item {
// 5. define a factory constructor
factory Item(
{
// 6. list all the arguments/properties
@Default(\"\") String website,
@Default(\"\") String description,
// ignore: invalid_annotation_target
@Default(false) @JsonKey(name: \'hosted_demo\') bool? hostedDemo,
@Default(\"\") String demo,
@Default(false) bool oss,
@Default(\"\") String source,
// ignore: invalid_annotation_target
@Default([]) @JsonKey(name: \'other-links\') List<OtherLinks> otherLinks,
@Default(\"\") String license
// 7. assign it with the `_Item` class constructor
}) = _Item;
// 8. define another factory constructor to parse from json
factory Item.fromJson(Map<String, dynamic> json) => _$ItemFromJson(json);
}
但我不知道如何将uniqueName 放入数据类。我检查过的大多数其他地方都假设 JSON 数据使用 JSON 对象内部的 uniqueName 格式化,并带有自己的密钥。虽然重构 JSON 文件是一种选择,但我宁愿不这样做。整个 JSON 文件大约 12000 行,重构起来很痛苦。
你们知道如何让uniqueName 进入数据类吗?
标签: json flutter dart flutter-freezed