I have the following class:
@JsonSerializable(explicitToJson: true)
class Section {
@JsonKey(name: '_id')
late String id;
late BaseInfo info;
@JsonKey(name: 'document_ids')
late List<String>? documentIds;
late List<String>? tags;
late List<Comment>? comments;
late List<UserBasedPermission>? permissions;
Section();
factory Section.fromJson(Map<String, dynamic> json) =>
_$SectionFromJson(json);
Map<String, dynamic> toJson() => _$SectionToJson(this);
}
Now when I try to call fromJson I get the error message that a Map<String, dynamic>
was expected but a _JsonMap
was found.
The code I use to convert it is as follows:
String test = '{"_id":"610b8ce9faa3695a81b93e98","info":{"name":"Mathematik","description":"Alles was mit Mathe zu tun hat Hurz ein Reh. Ein Hirsch 222 3333 444 555","active":false,"created_date":1628146903325,"created_by":"admin","last_update":null,"last_update_by":null,"last_comment":null,"deletion_date":null,"deleted_by":null,"locked_by":null,"locked_date":null,"object_type":"SECTION","version":6,"api_version":1},"document_ids":[],"tags":["mathematik","mathe","wissenschaft"],"comments":[{"user":"","timestamp":1628579634126,"comment":"Das ist ein Kommentar"},{"user":"admin","timestamp":1628580529698,"comment":"Noch ein Kommentar"}],"permissions":{"read_write_users":null,"read_only_users":null,"excluded_users":null}}';
Map<String, dynamic> parsedJson = jsonDecode(test);
print("parsedJson type: ${parsedJson.runtimeType} / $parsedJson");
Section sec = Section.fromJson(parsedJson);
I just can't figure out where the problem is here.
CodePudding user response:
Try creating the variable this way:
Map<String, dynamic> parsedJson = jsonDecode(test) as Map<String,dynamic>;
CodePudding user response:
Apparently there was some problem in the JsonSerializable annotation. After I changed it to @JsonSerializable(explicitToJson: true, includeIfNull: true, anyMap: false)
it works as expected.