Json_serializable.dart: Add casting support

Created on 13 Apr 2018  Â·  20Comments  Â·  Source: google/json_serializable.dart

I've integrated with a very bad API. Their JSON didn't have any types, it was all strings. It would be very usefull to have something like this:

{
  "ugly": "true",
}
@JsonSerializable()
class Example {
  Example({this.pretty});

  @JsonKey(
    name: 'ugly',
    fromJson: (v) => v == 'true',
    toJson: (v) => v.toString(),
  )
  final bool pretty;
}
enhancement

Most helpful comment

Far from done, but I have it bootstrapped - https://github.com/dart-lang/json_serializable/pull/146

All 20 comments

It might even solve #133

You'd have to use top-level methods, so that they are const. But that'd be doable...

running into a similar issue. firebase stores a field like "created_at" as a datetime, but the generated file builds this:

..createdAt = json['created_at'] == null
          ? null
          : DateTime.parse(json['created_at'] as String)

which breaks the parsing. im gonna explore your build_cli lib but itd be nice to have a way to get around this within this lib if possible. thanks!

Far from done, but I have it bootstrapped - https://github.com/dart-lang/json_serializable/pull/146

Firebase is another problem. The values it returns are JSON-like, but do
include non-JSON values like blobs, dates, geo points, etc.

On Tue, May 8, 2018 at 12:43 PM jmrboosties notifications@github.com
wrote:

running into a similar issue. firebase stores a field like "created_at" as
a datetime, but the generated file builds this:

..createdAt = json['created_at'] == null
? null
: DateTime.parse(json['created_at'] as String)

which breaks the parsing. im gonna explore your build_cli lib but itd be
nice to have a way to get around this within this lib if possible. thanks!

—
You are receiving this because you commented.
Reply to this email directly, view it on GitHub
https://github.com/dart-lang/json_serializable/issues/137#issuecomment-387519313,
or mute the thread
https://github.com/notifications/unsubscribe-auth/AABCiss7ylSqOTt7RivCy9N4J2-lbh55ks5twfVIgaJpZM4TT7yB
.

thanks. yea, firebase's handling of date is a bit unusual. it looks like if i were able to flag the field as such, it could parse correctly if the generated file just simple did createdAt = json['created_at']. the error i receive states that the type mismatch is String != DateTime, which is the type of createdAt

RE firebase.

You could always use https://pub.dartlang.org/documentation/json_serializable/0.5.0/json_serializable/JsonSerializableGenerator/JsonSerializableGenerator.html – and put in your own TypeHelper for DateTime that's a no-op.

thanks! ill have a look.

on the subject of Firebase, I'm getting this error when I try to use this lib to pull down a document from Firestore and turn it into an object:

I/flutter ( 5948): type '_InternalLinkedHashMap' is not a subtype of type 'Map' where
I/flutter ( 5948): _InternalLinkedHashMap is from dart:collection
I/flutter ( 5948): Map is from dart:core
I/flutter ( 5948): String is from dart:core

my interpretation is that the map from Firebase isnt explicitly typing its keys, whereas this json_serializable package is (to a string), causing the error. i double checked and i'm up to date on both packages.

Can the map from Firebase support non-String keys? If so, we should fix
that...

On Tue, May 8, 2018 at 9:24 PM jmrboosties notifications@github.com wrote:

on the subject of Firebase, I'm getting this error when I try to use this
lib to pull down a document from Firestore and turn it into an object:

I/flutter ( 5948): type '_InternalLinkedHashMap' is not
a subtype of type 'Map' where
I/flutter ( 5948): _InternalLinkedHashMap is from dart:collection
I/flutter ( 5948): Map is from dart:core
I/flutter ( 5948): String is from dart:core

my interpretation is that the map from Firebase isnt explicitly typing its
keys, whereas this json_serializable package is (to a string), causing the
error. i double checked and i'm up to date on both packages.

—
You are receiving this because you commented.
Reply to this email directly, view it on GitHub
https://github.com/dart-lang/json_serializable/issues/137#issuecomment-387616121,
or mute the thread
https://github.com/notifications/unsubscribe-auth/AABCirB70juNWtPykM2pqR3rKu3RyuqEks5twm-TgaJpZM4TT7yB
.

I don't know how it would exactly, but the map I'm getting back says key
should be dynamic, so I guess so?

On Tue, May 8, 2018, 9:28 PM Kevin Moore notifications@github.com wrote:

Can the map from Firebase support non-String keys? If so, we should fix
that...

On Tue, May 8, 2018 at 9:24 PM jmrboosties notifications@github.com
wrote:

on the subject of Firebase, I'm getting this error when I try to use this
lib to pull down a document from Firestore and turn it into an object:

I/flutter ( 5948): type '_InternalLinkedHashMap' is not
a subtype of type 'Map' where
I/flutter ( 5948): _InternalLinkedHashMap is from dart:collection
I/flutter ( 5948): Map is from dart:core
I/flutter ( 5948): String is from dart:core

my interpretation is that the map from Firebase isnt explicitly typing
its
keys, whereas this json_serializable package is (to a string), causing
the
error. i double checked and i'm up to date on both packages.

—
You are receiving this because you commented.
Reply to this email directly, view it on GitHub
<
https://github.com/dart-lang/json_serializable/issues/137#issuecomment-387616121
,
or mute the thread
<
https://github.com/notifications/unsubscribe-auth/AABCirB70juNWtPykM2pqR3rKu3RyuqEks5twm-TgaJpZM4TT7yB

.

—
You are receiving this because you commented.
Reply to this email directly, view it on GitHub
https://github.com/dart-lang/json_serializable/issues/137#issuecomment-387616539,
or mute the thread
https://github.com/notifications/unsubscribe-auth/AAuA1BaMN54ct0S8Z3vVzTTDMzTmjMEaks5twnBsgaJpZM4TT7yB
.

What method are you calling where it returns Map? What's
the stack trace?

On Tue, May 8, 2018 at 10:23 PM jmrboosties notifications@github.com
wrote:

I don't know how it would exactly, but the map I'm getting back says key
should be dynamic, so I guess so?

On Tue, May 8, 2018, 9:28 PM Kevin Moore notifications@github.com wrote:

Can the map from Firebase support non-String keys? If so, we should fix
that...

On Tue, May 8, 2018 at 9:24 PM jmrboosties notifications@github.com
wrote:

on the subject of Firebase, I'm getting this error when I try to use
this
lib to pull down a document from Firestore and turn it into an object:

I/flutter ( 5948): type '_InternalLinkedHashMap' is
not
a subtype of type 'Map' where
I/flutter ( 5948): _InternalLinkedHashMap is from dart:collection
I/flutter ( 5948): Map is from dart:core
I/flutter ( 5948): String is from dart:core

my interpretation is that the map from Firebase isnt explicitly typing
its
keys, whereas this json_serializable package is (to a string), causing
the
error. i double checked and i'm up to date on both packages.

—
You are receiving this because you commented.
Reply to this email directly, view it on GitHub
<

https://github.com/dart-lang/json_serializable/issues/137#issuecomment-387616121

,
or mute the thread
<

https://github.com/notifications/unsubscribe-auth/AABCirB70juNWtPykM2pqR3rKu3RyuqEks5twm-TgaJpZM4TT7yB
>

.

—
You are receiving this because you commented.
Reply to this email directly, view it on GitHub
<
https://github.com/dart-lang/json_serializable/issues/137#issuecomment-387616539
,
or mute the thread
<
https://github.com/notifications/unsubscribe-auth/AAuA1BaMN54ct0S8Z3vVzTTDMzTmjMEaks5twnBsgaJpZM4TT7yB

.

—
You are receiving this because you commented.
Reply to this email directly, view it on GitHub
https://github.com/dart-lang/json_serializable/issues/137#issuecomment-387623506,
or mute the thread
https://github.com/notifications/unsubscribe-auth/AABCitc_HnPKHfOHhj_iNXi1cBMvnBgfks5twn1IgaJpZM4TT7yB
.

The stack trace is just what I posted before, nothing more unfortunately

I/flutter ( 5948): type '_InternalLinkedHashMap<dynamic, dynamic>' is not a subtype of type 'Map<String, dynamic>' where
I/flutter ( 5948):   _InternalLinkedHashMap is from dart:collection
I/flutter ( 5948):   Map is from dart:core
I/flutter ( 5948):   String is from dart:core

This is the code that triggers it:

_firestore = Firestore.instance;

return _firestore.collection('favorites').where('user_id', isEqualTo: uid).getDocuments()
                .then((querySnap) {
                    querySnap.documents.forEach((document) {
                        print(document.data);

                        Map<String, dynamic> json = document.data; //casts, but if you put breaklines through this its that _InternalLinkedHashMap<dynamic, dynamic> type
                        Album album = new Album.fromJson(json['favorite_albums'][0]); //Throws the type exception
                    });
                })
                .catchError((error) {
                    print(error);
                });

The actual aim here is to just loop through the results and add them to a list, but I'm just manually grabbing object 0 here as part of my debugging, so forgive the loop for seemingly no reason haha.

Ah! You're using the Flutter firebase SDK. I was looking at the source for
https://github.com/firebase/firebase-dart

You should file an issue https://github.com/flutter/flutter/issues –
mention reference this discussion!

On Tue, May 8, 2018 at 11:31 PM jmrboosties notifications@github.com
wrote:

The stack trace is just what I posted before, nothing more unfortunately

I/flutter ( 5948): type '_InternalLinkedHashMap' is not a subtype of type 'Map' where
I/flutter ( 5948): _InternalLinkedHashMap is from dart:collection
I/flutter ( 5948): Map is from dart:core
I/flutter ( 5948): String is from dart:core

This is the code that triggers it:

_firestore = Firestore.instance;

return _firestore.collection('favorites').where('user_id', isEqualTo: uid).getDocuments()
.then((querySnap) {
querySnap.documents.forEach((document) {
print(document.data);

                  Map<String, dynamic> json = document.data; //casts, but if you put breaklines through this its that _InternalLinkedHashMap<dynamic, dynamic> type
                  Album album = new Album.fromJson(json['favorite_albums'][0]); //Throws the type exception
              });
          })
          .catchError((error) {
              print(error);
          });

The actual aim here is to just loop through the results and add them to a
list, but I'm just manually grabbing object 0 here as part of my debugging,
so forgive the loop for seemingly no reason haha.

—
You are receiving this because you commented.
Reply to this email directly, view it on GitHub
https://github.com/dart-lang/json_serializable/issues/137#issuecomment-387634454,
or mute the thread
https://github.com/notifications/unsubscribe-auth/AABCiv0CtVHjBIllP0foglsevs5D9osGks5two0tgaJpZM4TT7yB
.

ill do that, thanks!

I'm interested in trying those to/from json functions you can declare in the JsonKey. I see it committed to master, but you haven't made a release for it yet. I could pull down the source code of course but TBH I'm not sure how I would integrate that with my project if I did. Also, as a suggestion it might be nice to have a class-wide option for those to/from json functions, similar to how in Gson you can declare a custom deserializer for an entire class.

Thanks again

Thats awesome @kevmoo, thanks alot! Waiting for the release!!

@jmrboosties – release is coming soon

For whole classes, just add a toJson method and a fromJson ctor – it should work!

FYI – I published 0.51 here – but made a mistake w/ DateTime.

https://github.com/dart-lang/json_serializable/pull/149 Will fix it. Will get it out (as 0.5.2) today.

Was this page helpful?
0 / 5 - 0 ratings