有没有办法在dart中使用JsonSerializable创建JsonKey动态,我们可以从JsonSerializable类中创建并仅获取数组吗?

问题描述 投票:0回答:2

主要问题:如何使用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嵌入的简单示例:

  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”]

arrays json dart jsonserializer json-serializable
2个回答
0
投票

0
投票
© www.soinside.com 2019 - 2024. All rights reserved.