Uday
Uday

Reputation: 1719

Error : type 'String' is not a subtype of type 'Map<String, dynamic>' in type cast

I have a response

 [{details: {macId:789101112}}]

jsonData['details'] will return String {macId:789101112}

Parsing code :



fromJson(Map<String, dynamic> jsonData) => User(
        details: UserDetails.fromJson(jsonData['details'] as Map<String, dynamic>),
      );


class UserDetails{
 final String macId;
 UserDetails({this.macId});

 static UserDetails fromJson(Map<String, dynamic> json) =>
     UserDetails(macId: json['macId'] as String);
}

Upvotes: 1

Views: 762

Answers (1)

lrn
lrn

Reputation: 71773

Try looking at the original source. From your description, it sounds like it looks something like:

[{"details": "{\"macId\": 789101112}"}]

That is, the value of the "details" entry is a string containing JSON source code.

You will need to parse that a second time:

fromJson(Map<String, dynamic> jsonData) => 
  User(details: UserDetails.fromJson(jsonDecode(jsonData['details'])));

The reason for this is likely that the place where the you generate JSON data from UserDetails object, it calls jsonEncode on the map, and it should not do that. Just let the UserDetails-to-JSON function return a map, so that that map can be embedded in the larger JSON-like data structure. Then you won't need the second jsonDecode either.

Upvotes: 1

Related Questions