How to convert int timestamp to DateTime in json_serializable flutter - json

How can I convert an integer timestamp to Datetime.
Sample Code:
#JsonSerializable(nullable: false)
class Person {
final String firstName;
final String lastName;
final DateTime dateOfBirth;
Person({this.firstName, this.lastName, this.dateOfBirth});
factory Person.fromJson(Map<String, dynamic> json) => _$PersonFromJson(json);
Map<String, dynamic> toJson() => _$PersonToJson(this);
}
How do I convert dateOfBirth integer timeStamp to DateTime?

To convert an int timestamp to DateTime, you need to pass a static method that
returns a DateTime result to the fromJson parameter in the #JsonKey annotation.
This code solves the problem and allows the convertion.
#JsonSerializable(nullable: false)
class Person {
final String firstName;
final String lastName;
#JsonKey(fromJson: _fromJson, toJson: _toJson)
final DateTime dateOfBirth;
Person({this.firstName, this.lastName, this.dateOfBirth});
factory Person.fromJson(Map<String, dynamic> json) => _$PersonFromJson(json);
Map<String, dynamic> toJson() => _$PersonToJson(this);
static DateTime _fromJson(int int) => DateTime.fromMillisecondsSinceEpoch(int);
static int _toJson(DateTime time) => time.millisecondsSinceEpoch;
}
usage
Person person = Person.fromJson(json.decode('{"firstName":"Ada", "lastName":"Amaka", "dateOfBirth": 1553456553132 }'));

I use this:
#JsonSerializable()
class Person {
#JsonKey(fromJson: dateTimeFromTimestamp)
DateTime dateOfBirth;
...
}
DateTime dateTimeFromTimestamp(Timestamp timestamp) {
return timestamp == null ? null : timestamp.toDate();
}

Related

How to serialize patch request with optionals via json_serializable?

#JsonSerializable
class PatchUserDTO {
final String? name;
final DateTime? birthday;
...OTHER STAFF...
}
But I need to differentiate between birthday == null and birthday is not set.
I guess, nice solution would be
class Optional<T> {
final T? value;
Optional(this.value);
T? toJson() => value;
}
#JsonSerializable
class PatchUserDTO {
final String? name;
#JsonKey(includeIfNull: false)
final Optional<DateTime>? birthday;
...OTHER STAFF...
}
But includeIfNull is applied to finalised json. So if Optional<DateTime> is not null, but value is null, it still won't be serialized.

Dart/Flutter : convert BigInt to json

I have an object with a bigint property i want to encode to json string:
class Token {
Token(
{
this.name,
this.supply,
});
String? name;
BigInt? supply;
factory Token.fromJson(Map<String, dynamic> json) {
return Token(
name: json['name'],
supply: json['supply'] == null ? null : BigInt.parse(json['supply']),
);
}
Map<String, dynamic> toJson() => <String, dynamic>{
'name': name,
'supply': supply == null ? null : supply!.toString(),
};
}
I create a method to encode json to string...
String tokenToJson(Token data) => jsonEncode(data.toJson())
... but the format is not correct because i need a bigint in the format json and not a string:
the result i want:
{"name":"Token","supply":100000000000000,}
the result i obtain:
{"name":"Token","supply":"100000000000000",}
jsonEncode doesn't manage bigint type and i found on internet only solutions with a conversion of the bigint to a string type.
NB: Same issue with jsonDecode
Thx
use this simple method instead of BigInt use just "num"
import 'dart:convert';
void main() {
String data = '''{"name":"Token","supply":100000000000000}''';
print("supply: ${Token.fromJson(jsonDecode(data)).supply}");
}
class Token {
Token({
required this.name,
required this.supply,
});
late final String name;
late final num supply;
Token.fromJson(Map<String, dynamic> json){
name = json['name'];
supply = json['supply'];
}
Map<String, dynamic> toJson() {
final _data = <String, dynamic>{};
_data['name'] = name;
_data['supply'] = supply;
return _data;
}
}
Please check the following answer, instead of calling toString method on supply just call toInt method which will prevents the quotations and you will get the formatted json as expected
import 'dart:convert';
class Token {
Token(
{
this.name,
this.supply,
});
String? name;
BigInt? supply;
factory Token.fromJson(Map<String, dynamic> json) {
return Token(
name: json['name'],
supply: json['supply'] == null ? null :BigInt.from(json['supply']) ,
);
}
Map<String, dynamic> toJson() => <String, dynamic>{
'name': name,
'supply': supply == null ? null : supply!.toInt(),
};
String tokenToJson(Token data) => json.encode(data.toJson());
}
void main() {
Token token = Token(name: "token_one",supply : BigInt.parse("10000061234567"));
print(token.tokenToJson(token));
}
Output
{"name":"token_one","supply":10000061234567}
You don't need to parse, you can use from for convert int to BigInt
import 'dart:convert';
void main() {
String data = '''{"name":"Token","supply":100000000000000}''';
print(Token.fromJson(jsonDecode(data)).toJson());
}
class Token {
String? name;
double? supply;
Token({this.name, this.supply});
Token.fromJson(Map<String, dynamic> json) {
name = json['name'];
supply = json['supply'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = <String, dynamic>{};
data['name'] = name;
data['supply'] = supply;
return data;
}
}

Exception: type 'String' is not a subtype of type 'Map<String, dynamic>

Exception: type 'String' is not a subtype of type 'Map<String, dynamic>'
{"collection":{"data":"{\"id\": 1, \"name\": \"Marko\", \"picture\":
\"https://lh3.googleusercontent.com/a-/AAuE7mC1vqaKk_Eylt-fcKgJxuN96yQ7dsd2dBdsdsViK959TKsHQ=s96-
c\"}","statusCode":202,"version":"1.0"}}
This is the above json and i want to put it at User pojo class only the [data].
But it threw the above exception type.
class UserCollection {
final User data;
final int statusCode;
final String version;
UserCollection({this.data, this.statusCode, this.version});
factory UserCollection.fromJson(Map<String, dynamic> json) {
return UserCollection(
statusCode: json['statusCode'] as int,
data: User.fromJson(json['data']) ,
version: json['version'] as String );
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['data'] = this.data;
data['statusCode'] = this.statusCode;
data['version'] = this.version;
return data;
}
}
User Pojo class
#JsonSerializable()
class User {
final int id;
final String sub;
final String home;
final String work;
final String name;
final String mobileNo;
final String email;
final String favMechId;
final String appVersionCode;
final String picture;
final String serverTime;
final String dateCreated;
final String dateModified;
final String fcmTokenId;
User(
{this.id,
this.sub,
this.home,
this.work,
this.name,
this.mobileNo,
this.email,
this.favMechId,
this.appVersionCode,
this.picture,
this.serverTime,
this.dateCreated,
this.dateModified,
this.fcmTokenId});
factory User.fromJson(Map<String, dynamic> json) => _$UserFromJson(json);
Map<String,dynamic> toJson() => _$UserToJson(this);
I have referring this medium site for clarity, medium flutter json
but in vein more than 4 hours i couldn't what was wrong.
If change the User.from() to String then it's okay. But i need to parse the [data] from json to User pojo class.
Try below,
factory UserCollection.fromJson(Map<String, dynamic> json) {
return UserCollection(
statusCode: json['statusCode'] as int,
data: User.fromJson(json.decode(json['data'])),
version: json['version'] as String );
}
Change in data: User.fromJson(json.decode(json['data'])),

Dart json serialization, how to deal with _id from mongodb being private in Dart?

I'm using automatic serialization/deserialization in dart like mentioned here
import 'package:json_annotation/json_annotation.dart';
part 'billing.g.dart';
#JsonSerializable()
class Billing {
Billing(){}
String _id;
String name;
String status;
double value;
String expiration;
factory Billing.fromJson(Map<String, dynamic> json) => _$BillingFromJson(json);
Map<String, dynamic> toJson() => _$BillingToJson(this);
}
But in order for the serialization/deserialization to work, the fields must be public. However, in Dart, a field with _ at the beggining is private. So I can't use _id from mongodb to serialize/deserialize things.
How can I overcome this?
You can use #JsonKey annotation. Refer https://pub.dev/documentation/json_annotation/latest/json_annotation/JsonKey/name.html
import 'package:json_annotation/json_annotation.dart';
part 'billing.g.dart';
#JsonSerializable()
class Billing {
Billing(){}
// Tell json_serializable that "_id" should be
// mapped to this property.
#JsonKey(name: '_id')
String id;
String name;
String status;
double value;
String expiration;
factory Billing.fromJson(Map<String, dynamic> json) => _$BillingFromJson(json);
Map<String, dynamic> toJson() => _$BillingToJson(this);
}

Dart: How to de-serialize a list of objects

I have a class "SnapShot" with some member variables like a DateTime and a double. I have written the fromJson / toJson like this:
class SnapShot {
SnapShot (this.date, this.value);
final DateTime date;
final double value;
SnapShot.fromJson(Map<String, dynamic> json)
: date = DateTime.parse(json['date']),
value = json['value']();
Map<String, dynamic> toJson() =>
{
'date': date.toString(),
'value': value
};
}
I need to (de)serialize a list of these objects (List) to/from json file.
What is the correct way to do this?
This should do the trick:
import 'dart:convert';
class SnapShot {
SnapShot(this.date, this.value);
final DateTime date;
final double value;
SnapShot.fromJson(Map<String, dynamic> json)
: date = DateTime.parse(json['date']),
value = json['value'];
Map<String, dynamic> toJson() => {'date': date.toString(), 'value': value};
#override
String toString() => 'date: $date, value: $value';
}
void main() {
final list = [SnapShot(DateTime.now(), 0.4), SnapShot(DateTime.now(), 1.5)];
final asJson = json.encode(list);
final decodedJson = json.decode(asJson) as List;
final snapShots = decodedJson.map((map) => SnapShot.fromJson(map)).toList();
print(snapShots);
}