flutterdartjson-serializationjson-serializablejson-annotation

Flutter error: _InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'Map<String, ItemStatus>


I am using json_annotation to generate the fromJson and toJson functions for my custom class ItemStatus:

import 'package:json_annotation/json_annotation.dart';
part 'item.g.dart';

@JsonSerializable(explicitToJson: true, anyMap: true)
class ItemStatus {
  final String id;
  int vote = 0;
  bool saved = false;
  bool postRead = false;
  bool articleRead = false;

  ItemStatus({required this.id});

  //generate using: flutter pub run build_runner build --delete-conflicting-outputs
  factory ItemStatus.fromJson(Map<String, dynamic> json) => _$ItemStatusFromJson(json);
  Map<String, dynamic> toJson() => _$ItemStatusToJson(this);
}

The encoding works fine however when I try to decode it back to ItemStatus, it throws an error:

type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'ItemStatus'

Here's me trying to do the encoding and decoding:

try {
      final itemStatus = ItemStatus(id: "abcd123");
      itemStatus.saved = true;

      final jsonString = jsonEncode(itemStatus);
      print("jsonString: $jsonString");

      ItemStatus decoded = jsonDecode(jsonString);
      print("decoded: $decoded");
    } catch (e) {
      print("Error: $e");
    }

What am I doing wrong?


Solution

  • You can't decode an object. You need to use toJson and fromJson like this:

    final jsonString = jsonEncode(ItemStatus. toJson(itemStatus));
    print("jsonString: $jsonString");
    

    and decode it like this:

    ItemStatus decoded = ItemStatus.fromJson(jsonDecode(jsonString));
    print("decoded: $decoded");