Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Deserialize a DateTime from two sources in different formats #857

Closed
elvis-gbmme opened this issue Apr 25, 2020 · 2 comments
Closed

Deserialize a DateTime from two sources in different formats #857

elvis-gbmme opened this issue Apr 25, 2020 · 2 comments

Comments

@elvis-gbmme
Copy link

Hi,
I have a built_value class that gets data from two sources (firestore and elasticsearch). The two formats are Firestore in DateTime and elastic in DateTime as String.

I'm already using the following serializers StandardJsonPlugin, TimestampSerializerPlugin (#541) and GeopointSerializerPlugin

The firesstore data is working fine after using the TimestampSerializer, but the elasticsearch sends the DateTime in a string format which causes the following exception
failed due to: Deserializing '2019-07-22T09:43:01.000Z' to 'DateTime' failed due to: type 'String' is not a subtype of type 'int' in type cast

I found #454 to be close to my issue and tried using it, but it breaks even my firestore serialization with the error Unhandled Exception: type '_TypeError' is not a subtype of type 'Exception'.

Kindly help.

Thanks.

@raulmabe
Copy link

raulmabe commented Apr 26, 2020

I am currently dealing with this exact issue.
Deserializing '1998-04-02T05:35:55.000Z' to 'DateTime' failed due to: type 'String' is not a subtype of type 'int' in type cast)

I added this plugin to the serializer and now it works (I didn't achieved to serialize it with the same format it was deserialized, but still):

import 'package:built_value/serializer.dart';

class DateTimeSerializerPlugin implements SerializerPlugin {
  @override
  Object beforeSerialize(Object object, FullType specifiedType) {
    if (specifiedType.root != DateTime) return object;
    return DateTime.parse(object.toString()).toUtc();
  }

  @override
  Object afterSerialize(Object object, FullType specifiedType) => object;

  @override
  Object beforeDeserialize(Object object, FullType specifiedType) {
    if (specifiedType.root != DateTime) return object;
    return DateTime.parse(object as String).toUtc().microsecondsSinceEpoch;
  }

  @override
  Object afterDeserialize(Object object, FullType specifiedType) => object;
}

@davidmorgan
Copy link
Collaborator

This requires #1046

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants