using json serializable on a received array instead of an object - Is it possible ?

241 views
Skip to first unread message

Adam Zedan

unread,
May 19, 2018, 3:15:04 PM5/19/18
to Flutter Dev
I am currently receiving something like this as json
[
  {
    "employee": {
      "user": {
        "first_name": "...",
        "last_name": "Mob",
      },
      "employee_zip": 12345,
    },
  }
]

Notice the above is an array and not an object. This is what my dart file looks like
@JsonSerializable()
class myList extends Object with _$myListSerializerMixin {

@JsonKey(name: "")
final List<myResponse> response;

myList(this.response);

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

Now when I try to do the following 

myList foo = myList.fromJson(json.decode(response));

I get the exception:

[VERBOSE-2:dart_error.cc(16)] Unhandled exception:
type 'List<dynamic>' is not a subtype of type 'Map<String, dynamic>' where
  List is from dart:core
  Map is from dart:core
  String is from dart:core

Any suggestions on how I can fix this ?

Thetyne

unread,
May 19, 2018, 5:51:42 PM5/19/18
to Flutter Dev
you need multiple class like :

class Employe
{
Employe(...);
User user;
}

class User
{
User (...);
String first_name;
String last_name;
}

class Foo{

Foo(...)

Employe employee;
String imageA;
}


and after serialization ((each class need serializable attribute and internal parser):

final parsed = json.decode(response).cast<Map<String, dynamic>>();
List<Foo> fooList = parsed.map<Foo>((json) => new Foo.fromJson(json)).toList();

Kris Giesing

unread,
May 20, 2018, 1:01:23 AM5/20/18
to Thetyne, Flutter Dev
If I'm understanding the situation, then I think that cast will fail? If the decoded JSON object really is a list, not a map, it's the List.cast method that would be invoked.

To the OP: I think your fromJson method needs to take dynamic, and do something different depending on whether the input is a list or a map. You can use the type test operators for this kind of thing. I'm not entirely sure what you want out of the JSON list, but you could for example extract the first element of the list and use that for the map your method originally required.

Note that this is more a general Dart question than a Flutter question.

Hope this helps,

- Kris

--
You received this message because you are subscribed to the Google Groups "Flutter Dev" group.
To unsubscribe from this group and stop receiving emails from it, send an email to flutter-dev+unsubscribe@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Kris Giesing

unread,
May 20, 2018, 1:02:59 AM5/20/18
to Thetyne, Flutter Dev
@Thetyne: Whoops, actually, I misinterpreted what you wrote. You're casting the list to a list of maps, which would also work.
Reply all
Reply to author
Forward
0 new messages