主要问题:如何使用 json_serializable 解析这个 json 数组?
[
{
"albumId": 1,
"id": 1,
"title": "accusamus beatae ad facilis cum similique qui sunt",
"url": "http://placehold.it/600/92c952",
"thumbnailUrl": "http://placehold.it/150/92c952"
},
{
"albumId": 1,
"id": 2,
"title": "reprehenderit est deserunt velit ipsam",
"url": "http://placehold.it/600/771796",
"thumbnailUrl": "http://placehold.it/150/771796"
},
{
"albumId": 1,
"id": 3,
"title": "officia porro iure quia iusto qui ipsa ut modi",
"url": "http://placehold.it/600/24f355",
"thumbnailUrl": "http://placehold.it/150/24f355"
}
]
使用自定义对象的 StringList inlace 的简单示例:
import 'package:json_annotation/json_annotation.dart';
part 'all_json.g.dart';
@JsonSerializable()
class AllJsonData {
@JsonKey(name: 'some_key') // @Question: Can we make this some_key dynamic
List<String> orders;
AllJsonData(this.orders);
factory AllJsonData.fromJson(Map<String, dynamic> json) =>
_$AllJsonDataFromJson(json);
Map<String, dynamic> toJson() => _$AllJsonDataToJson(this);
}
all_json.g.dart
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'all_json.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
AllJsonData _$AllJsonDataFromJson(Map<String, dynamic> json) {
return AllJsonData(
(json['some_key'] as List)?.map((e) => e as String)?.toList(),
);
}
Map<String, dynamic> _$AllJsonDataToJson(AllJsonData instance) =>
<String, dynamic>{
'some_key': instance.orders,
};
@Question1:我们可以让这个 some_key 动态吗?在制作对象并反序列化后,它会给出这样的结果。
AllJsonData allJsonData = AllJsonData(['Some', 'People']);
String vv = jsonEncode(allJsonData.toJson());
print(vv);
// Getting output like:
"{"education":["Some","People"]}"
// Required Output only array without key:
["Some","People"]
@Question2:如何获得没有键的只有数组的输出: [“Some”,“People”]