Skip to content

Serialization fails: type 'String' is not a subtype of type 'int' in type cast #503

Closed
@broofus

Description

@broofus

It seems that the fromJson needs to parse an int instead of casting the String to an int.

Dart Version:

Dart VM version: 2.3.0-dev.0.1.flutter-1f1592edce (Tue Apr 23 00:32:54 2019 +0000) on "linux_x64"

pubspec.yaml :

 environment:
  sdk: '>=2.2.0 <3.0.0'

dependencies:
  json_annotation: ^2.4.0

dev_dependencies:
  pedantic: ^1.0.0
  test: ^1.0.0
  build_runner: ^1.6.0
  json_serializable: ^3.0.0

Annotated class:

import 'package:json_annotation/json_annotation.dart';

part 'json.g.dart';

@JsonSerializable()
class JsonObject extends Object {
  final int number;

  JsonObject(this.number);

  factory JsonObject.fromJson(Map<String, dynamic> json) => _$JsonObjectFromJson(json);
}

Generated class:

part of 'json.dart';

// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************

JsonObject _$JsonObjectFromJson(Map<String, dynamic> json) {
  return JsonObject(json['number'] as int);
}

Map<String, dynamic> _$JsonObjectToJson(JsonObject instance) =>
    <String, dynamic>{'number': instance.number};

Function using class:

import 'dart:convert';
import 'json.dart';

int calculate() {
  final String jsonString = '{"number": "5"}';
  final Map<String, dynamic> jsonMap = jsonDecode(jsonString);
  JsonObject jsonObject = JsonObject.fromJson(jsonMap);
  int number = jsonObject.number;

  return number * 6;
}

Error message:

Unhandled exception:
type 'String' is not a subtype of type 'int' in type cast
#0 _$JsonObjectFromJson
package:serializer_fail/json.g.dart:10
#1 new JsonObject.fromJson
package:serializer_fail/json.dart:11
#2 calculate
package:serializer_fail/serializer_fail.dart:7
#3 main
../bin/main.dart:4
#4 _startIsolate. (dart:isolate-patch/isolate_patch.dart:298:32)
#5 _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:171:12)

If I hand edit the generated class to change it from a cast to parsing an int the program works.

Edited generated class:

-  return JsonObject(json['number'] as int);
+  return JsonObject(int.parse(json['number']));

Exception is now gone:

Hello world: 30!
Exited

Thanks.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions