jack
jack

Reputation: 17

why json serializer to model class error?

json

{
"status":1,
"error":"error",
"data":{"id":10000,"email":"[email protected]"}
}

the data field is an arbitrary type of data

models.dart

import 'package:flutter/material.dart';

class User {
  int id;
  String email;

  User({
    @required this.id,
    @required this.email,
  });
}

class Response<T> {
  final int status;
  final String error;
  final T data;

  const Response({
    this.status,
    this.error,
    this.data,
  });

  factory Response.formJson(Map<String, dynamic> json) {
    return Response(
      status: json["status"] as int,
      error: json["error"] as String,
      data: (json["data"] as T),
    );
  }
}

user.dart

class User {
  int id;
  String email;

  User({
    this.id,
     this.email,
  });
}

code

Response resp = Response<User>.formJson(json);
print(resp.status);
print(resp.error);
print(resp.data);

exception

Unhandled Exception: type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'User' in type cast

how to deal with it? Does it need to be serialized again?

Upvotes: 0

Views: 679

Answers (1)

Christopher Moore
Christopher Moore

Reputation: 17151

json["data"] is essentially a type of Map<String, dynamic>. There is no implicit cast to your User object so you have to explicitly cast that Map to a User. To do this you can do essentially the same thing you did with Response's factory constructor.

Changes to User class:

class User {
  int id;
  String email;

  User({
    @required this.id,
    @required this.email,
  });

  factory User.fromJson(Map<String, dynamic> json) {
    return User(
      id: json["id"],
      email: json["email"],
    );
  }
}

Changes to Response.formJson:

factory Response.formJson(Map<String, dynamic> json) {
    return Response(
      status: json["status"] as int,
      error: json["error"] as String,
      data: User.fromJson(json["data"]), //or T.fromJson is that is a required capability and all your possible T's will have a fromJson constructor
    );
  }

Upvotes: 1

Related Questions