Search code examples
arraysjsondartjsonserializerjson-serializable

Is there any way to create JsonKey dynamic using JsonSerializable in dart and can we create and get only array from the JsonSerializable class?


Main Question: How to parse this json array using json_serializable?

  [
  {
    "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"
  }
]

Simple Example using StringList inlace of custom object:

  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: Can we make this some_key dynamic? After making the object and deserializing, it give the result like this.

    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: How to get the output like only array without key: ["Some","People"]


Solution

  • To convert model from JsonArray to String using simple String[].

            AllJsonData allJsonData = AllJsonData(
              orders: ['James', 'Bipin', 'Simon'],
            );
            String jsonObjectAsString = jsonEncode(allJsonData.toJson());
            var parentMap = jsonDecode(jsonObjectAsString);
    
            // @read: To convert as JsonString
            var jsonString = jsonEncode(parentMap['orders'],
                toEncodable: (e) => e.toString());
            print(jsonObjectAsString); 
           // gives result like "["James","Bipin","Simon"]"
    

    For Custom Model class:

            AllJsonData allJsonData = AllJsonData(
              education: edu,
            );
            String jsonObjectAsString = jsonEncode(allJsonData.toJson());
            var parentMap = jsonDecode(jsonObjectAsString);
            var subParentMap = parentMap['education'];
            List<dynamic> mList = subParentMap['modelList'];
            // mapping as model-list
            var modelList =
                mList.map((e) => ExpPopupModel.fromJson(e)).toList();
            // convert into json-string
            var jsonString = jsonEncode(subParentMap['modelList'],
                toEncodable: (e) => e.toString());
            print(jsonObjectAsString);