I am trying to generate fromJSON and toJson functions for my nested objects using the json_serializable library. But when I tried to use the generated functions, I got an error with deserialization of the nested object.
I think I understand how to write toJSON and FromJSON functions. But I want to figure out how to work with the json_serializable library and work with the generated code.
Class with models:
import 'package:json_annotation/json_annotation.dart';
part 'models.g.dart';
#JsonSerializable()
class OfficesList {
List<Office> offices;
OfficesList({required this.offices});
factory OfficesList.fromJson(Map<String, dynamic> json) => _$OfficesListFromJson(json);
Map<String, dynamic> toJson() => _$OfficesListToJson(this);
}
#JsonSerializable()
class Office {
final String name;
final String address;
final String image;
Office({required this.name, required this.address, required this.image});
factory Office.fromJson(Map<String, dynamic> json) => _$OfficeFromJson(json);
Map<String, dynamic> toJson() => _$OfficeToJson(this);
}
Generated class:
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'models.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
OfficesList _$OfficesListFromJson(Map<String, dynamic> json) => OfficesList(
offices: (json['offices'] as List<dynamic>)
.map((e) => Office.fromJson(e as Map<String, dynamic>))
.toList(),
);
Map<String, dynamic> _$OfficesListToJson(OfficesList instance) =>
<String, dynamic>{
'offices': instance.offices,
};
Office _$OfficeFromJson(Map<String, dynamic> json) => Office(
name: json['name'] as String,
address: json['address'] as String,
image: json['image'] as String,
);
Map<String, dynamic> _$OfficeToJson(Office instance) => <String, dynamic>{
'name': instance.name,
'address': instance.address,
'image': instance.image,
};
void main(){
Office of1 = Office(name: "pupa", address: "lupa", image: "image");
Office of2 = Office(name: "lupa", address: "pupa", image: "image");
OfficesList list1 = OfficesList(offices: [of1,of2]);
OfficesList list2 = OfficesList.fromJson(list1.toJson());
print(list2.toJson());
}
The exception in these lines
OfficesList list2 = OfficesList.fromJson(list1.toJson())
.map((e) => Office.fromJson(e as Map<String, dynamic>))
Unhandled exception:
type 'Office' is not a subtype of type 'Map<String, dynamic>' in type cast
#0 _$OfficesListFromJson.<anonymous closure> (package:jsom_test/models.g.dart:11:41)
#1 MappedListIterable.elementAt (dart:_internal/iterable.dart:413:31)
#2 ListIterator.moveNext (dart:_internal/iterable.dart:342:26)
#3 new _GrowableList._ofEfficientLengthIterable (dart:core-patch/growable_array.dart:189:27)
#4 new _GrowableList.of (dart:core-patch/growable_array.dart:150:28)
#5 new List.of (dart:core-patch/array_patch.dart:51:28)
#6 ListIterable.toList (dart:_internal/iterable.dart:213:44)
#7 _$OfficesListFromJson (package:jsom_test/models.g.dart:12:12)
#8 new OfficesList.fromJson (package:jsom_test/models.dart:9:62)
#9 main (package:jsom_test/json_test.dart:9:35)
#10 _delayEntrypointInvocation.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:297:19)
#11 _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:192:12)
Related
I am trying to fetch and parse the below response . I am successfull in receiving the json but unable to parse the array of objects . I am using serializable for this . kindly help me .
Following below is the model class
import 'package:coinbase_sockets/deriv_models/active_symbols_response.dart';
import 'package:json_annotation/json_annotation.dart';
part 'markets_response.g.dart';
#JsonSerializable()
class MarketsResponse {
#JsonKey(name: 'active_symbols')
List<ActiveSymbolsResponse> active_symbols;
MarketsResponse(this.active_symbols);
factory MarketsResponse.fromJson(Map<String,dynamic> data) {
print('##---------------------coming--------------------------');
var l = _$MarketsResponseFromJson(data);
print('##lrngth l'+l.toString());
return _$MarketsResponseFromJson(data);}
Map<String,dynamic> toJson() => _$MarketsResponseToJson(this);
}
Below is the generated class that i edited .
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'markets_response.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
MarketsResponse _$MarketsResponseFromJson(Map<String, dynamic> json) {
**print('##---------------------market--------------------------'+json.toString()); receved upto here**
var mm= MarketsResponse(
json['active_symbols'] as List<ActiveSymbolsResponse>
);
**print('##---------------------mm--------------------------');this is not printed -means issue with mm**
return MarketsResponse(
json['active_symbols'] as List<ActiveSymbolsResponse>
);
}
Map<String, dynamic> _$MarketsResponseToJson(MarketsResponse instance) =>
<String, dynamic>{
'active_symbols': instance.active_symbols,
};
Try this
import 'package:json_annotation/json_annotation.dart';
part 'markets_response.g.dart';
#JsonSerializable()
class MarketsResponse {
#JsonKey(name: 'active_symbols')
List<ActiveSymbolsResponse> active_symbols;
MarketsResponse(this.active_symbols);
factory MarketsResponse.fromJson(Map<String, dynamic> json) => _$MarketsResponseFromJson(json);
Map<String, dynamic> toJson() => _$MarketsResponseToJson(this);
}
hi does anyone of you know how to parse a list of objects from a json string since everything has to be annotated?
i have the following code
import './utils.dart';
import 'dart:convert';
import 'package:hex/hex.dart';
import 'package:crypto/crypto.dart';
import 'dart:isolate';
import 'package:gladiators/models/constantes.dart';
class InterioreRationem {
final String publicaClavis;
BigInt nonce;
final String id;
InterioreRationem(this.publicaClavis, this.nonce): id = Utils.randomHex(32);
InterioreRationem.incipio(this.publicaClavis):
nonce = BigInt.zero,
id = Utils.randomHex(32);
mine() {
nonce += BigInt.one;
}
Map<String, dynamic> toJson() => {
'publicaClavis': publicaClavis,
'nonce': nonce.toString(),
'id': id
};
InterioreRationem.fromJson(Map<String, dynamic> jsoschon):
publicaClavis = jsoschon['publicaClavis'].toString(),
nonce = BigInt.parse(jsoschon['nonce'].toString()),
id = jsoschon['id'].toString();
}
class Propter {
late String probationem;
final InterioreRationem interioreRationem;
Propter(this.probationem, this.interioreRationem);
Propter.incipio(this.interioreRationem):
probationem = HEX.encode(sha256.convert(utf8.encode(json.encode(interioreRationem.toJson()))).bytes);
static void quaestum(List<dynamic> argumentis) {
InterioreRationem interioreRationem = argumentis[0] as InterioreRationem;
SendPort mitte = argumentis[1] as SendPort;
String probationem = '';
int zeros = 1;
while (true) {
do {
interioreRationem.mine();
probationem = HEX.encode(sha256.convert(utf8.encode(json.encode(interioreRationem.toJson()))).bytes);
} while(!probationem.startsWith('0' * zeros));
zeros += 1;
mitte.send(Propter(probationem, interioreRationem));
}
}
Map<String, dynamic> toJson() => {
'probationem': probationem,
'interioreRationem': interioreRationem.toJson()
};
Propter.fromJson(Map<String, dynamic> jsoschon):
probationem = jsoschon['probationem'].toString(),
interioreRationem = InterioreRationem.fromJson(jsoschon['interioreRationem'] as Map<String, dynamic>);
bool isProbationem() {
if (probationem == HEX.encode(sha256.convert(utf8.encode(json.encode(interioreRationem.toJson()))).bytes)) {
return true;
}
return false;
}
}
class GladiatorInput {
final int index;
final String signature;
final String gladiatorId;
GladiatorInput(this.index, this.signature, this.gladiatorId);
Map<String, dynamic> toJson() => {
'index': index,
'signature': signature,
'gladiatorId': gladiatorId
};
GladiatorInput.fromJson(Map<String, dynamic> jsoschon):
index = int.parse(jsoschon['index'].toString()),
signature = jsoschon['signature'].toString(),
gladiatorId = jsoschon['gladiatorId'].toString();
}
class GladiatorOutput {
final List<Propter> rationem;
final String defensio;
GladiatorOutput(this.rationem): defensio = Utils.randomHex(1);
Map<String, dynamic> toJson() => {
'rationem': rationem.map((r) => r.toJson()).toList(),
'defensio': defensio
};
GladiatorOutput.fromJson(Map<String, dynamic> jsoschon):
rationem = List<Propter>.from(jsoschon['rationem'].map((r) => Propter.fromJson(r as Map<String, dynamic>)) as List<dynamic>),
defensio = jsoschon['defensio'].toString();
}
class Gladiator {
final GladiatorInput? input;
final List<GladiatorOutput> outputs;
final String random;
final String id;
Gladiator(this.input, this.outputs, this.random):
id = HEX.encode(
sha512.convert(
utf8.encode(json.encode(input?.toJson())) +
utf8.encode(json.encode(outputs.map((o) => o.toJson()).toList())) +
utf8.encode(random)).bytes);
Map<String, dynamic> toJson() => {
'input': input?.toJson(),
'outputs': outputs.map((o) => o.toJson()).toList(),
'random': random,
'id': id
};
Gladiator.fromJson(Map<String, dynamic> jsoschon):
input = jsoschon['input'] != null ? GladiatorInput.fromJson(jsoschon['input'] as Map<String, dynamic>) : null,
outputs = List<GladiatorOutput>.from(jsoschon['outputs'].map((o) => GladiatorOutput.fromJson(o as Map<String, dynamic>)) as List<dynamic>),
random = jsoschon['random'].toString(),
id = jsoschon['id'].toString();
static List<Propter> grab(int difficultas, List<Propter> propters) {
List<Propter> reditus = [];
for (int i = 64; i >= difficultas; i--) {
if(reditus.length < Constantes.perRationesObstructionum) {
reditus.addAll(propters.where((p) => p.probationem.startsWith('0' * difficultas) && !reditus.contains(p)));
} else {
break;
}
}
return reditus;
}
}
so i dont know how to convert a list of objects no more
i was jused to map it and call the fromjson method upon it but all of a sudden i have to annotate everything and i dont know whats the proper annotation for objects from a json string
does anyone know how to convert since the update?
i have the following error
-- Conduit CLI Version: 3.1.2
-- Conduit project version: 3.1.2
-- Starting application 'gladiators/gladiators'
Channel: GladiatorsChannel
Config: /home/noahbergh/gladiators/config.yaml
Port: 8888
[INFO] conduit: Server conduit/1 started.
#0 new Gladiator.fromJson (package:gladiators/models/gladiator.dart:112:128)
#1 new InterioreObstructionum.fromJson (package:gladiators/models/obstructionum.dart:214:29)
#2 new Obstructionum.fromJson (package:gladiators/models/obstructionum.dart:303:55)
#3 Utils.priorObstructionum (package:gladiators/models/utils.dart:38:21)
<asynchronous suspension>
#4 ObstructionumController.numerus (package:gladiators/controllers/obstructionum_controller.dart:13:27)
<asynchronous suspension>
#5 ResourceController._process (package:conduit/src/http/resource_controller.dart:363:22)
<asynchronous suspension>
#6 Controller.receive (package:conduit/src/http/controller.dart:162:24)
<asynchronous suspension>
[SEVERE] conduit: GET /obstructionum 95ms 500 {user-agent : Mozilla/5.0 (X11; CrOS x86_64 14588.123.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.72 Safari/537.36\nconnection : keep-alive\nsec-ch-ua-mobile : ?0\ncache-control : no-cache\nsec-fetch-dest : empty\npostman-token : dfb826a1-433b-db3b-5260-c65fe007fa93\naccept-encoding : gzip, deflate, br\nsec-fetch-site : none\naccept : */*\naccept-language : nl,en;q=0.9\nsec-fetch-mode : cors\nhost : localhost:8888\nsec-ch-ua-platform : "Chrome OS"\nsec-ch-ua : " Not A;Brand";v="99", "Chromium";v="101", "Google Chrome";v="101"\n} type 'MappedListIterable<dynamic, dynamic>' is not a subtype of type 'List<dynamic>' in type cast #0 new Gladiator.fromJson (package:gladiators/models/gladiator.dart:112:128)
#1 new InterioreObstructionum.fromJson (package:gladiators/models/obstructionum.dart:214:29)
#2 new Obstructionum.fromJson (package:gladiators/models/obstructionum.dart:303:55)
#3 Utils.priorObstructionum (package:gladiators/models/utils.dart:38:21)
<asynchronous suspension>
#4 ObstructionumController.numerus (package:gladiators/controllers/obstructionum_controller.dart:13:27)
<asynchronous suspension>
#5 ResourceController._process (package:conduit/src/http/resource_controller.dart:363:22)
<asynchronous suspension>
#6 Controller.receive (package:conduit/src/http/controller.dart:162:24)
<asynchronous suspension>
^[[B^C-- Stopping application.
Reason: Process interrupted.
how can I re-create objects from a serialized/deserialized map of objects?
import 'dart:convert';
class InternalTx {
int a;
bool b;
InternalTx(this.a, this.b);
factory InternalTx.fromJson(Map<String, dynamic> json) =>
InternalTxFromJson(json);
Map<String, dynamic> toJson() => InternalTxToJson(this);
}
InternalTx InternalTxFromJson(Map<String, dynamic> json) => InternalTx(
json['a'] as int,
json['b'] as bool,
);
Map<String, dynamic> InternalTxToJson(InternalTx instance) => <String, dynamic>{
'a': instance.a,
'b': instance.b,
};
main() {
Map<String, InternalTx> m = {};
for (int i=0; i<10; i++)
{
InternalTx itx = InternalTx(i, false);
m["Hello: $i"] = itx;
}
String serM = jsonEncode(m);
print(serM);
////SERILIZED OKAY
Map<String, dynamic> n = jsonDecode(serM);
InternalTx newItx = n["Hello: 0"]; <-- Problem here.
print(newItx);
}
Output:
{"Hello: 0":{"a":0,"b":false},"Hello: 1":{"a":1,"b":false},"Hello: 2":{"a":2,"b":false},"Hello: 3":{"a":3,"b":false},"Hello: 4":{"a":4,"b":false},"Hello: 5":{"a":5,"b":false},"Hello: 6":{"a":6,"b":false},"Hello: 7":{"a":7,"b":false},"Hello: 8":{"a":8,"b":false},"Hello: 9":{"a":9,"b":false}}
Uncaught Error: TypeError: Instance of '_JsonMap': type '_JsonMap' is not a subtype of type 'InternalTx'
What is missing here to deserialize the map of objects correctly?
Thanks!
You need to actually call the InternalTx.fromJson constructor since this is not done automatically. So your last piece of code should be:
////SERILIZED OKAY
Map<String, dynamic> n = jsonDecode(serM);
InternalTx newItx = InternalTx.fromJson(n["Hello: 0"]);
print(newItx); // Instance of 'InternalTx'
I may need help with this. Basically im getting this exception when calling order.toJson() method. I have been checking the code but seems good for me. If you see an error please let me know.
E/flutter ( 5623): [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception:
Converting object to an encodable object failed: Instance of 'OrderItem'
E/flutter ( 5623): #0 _JsonStringifier.writeObject (dart:convert/json.dart:688:7)
E/flutter ( 5623): #1 _JsonStringifier.writeList (dart:convert/json.dart:736:7)
E/flutter ( 5623): #2 _JsonStringifier.writeJsonValue (dart:convert/json.dart:718:7)
E/flutter ( 5623): #3 _JsonStringifier.writeObject (dart:convert/json.dart:679:9)
E/flutter ( 5623): #4 _JsonStringStringifier.printOn (dart:convert/json.dart:877:17)
E/flutter ( 5623): #5 _JsonStringStringifier.stringify (dart:convert/json.dart:862:5)
E/flutter ( 5623): #6 JsonEncoder.convert (dart:convert/json.dart:262:30)
E/flutter ( 5623): #7 JsonCodec.encode (dart:convert/json.dart:172:45)
When calling toJson() method. Here are my classes.
class Order{
String id;
String userId;
String deliverId;
String restaurantId;
List<OrderItem> orderItems;
double total;
String orderStatus;
Order({
required this.id,
required this.userId,
required this.deliverId,
required this.restaurantId,
required this.orderItems,
required this.total,
required this.orderStatus
});
Map<String, dynamic> toJson(){
return {
'id' : id,
'userId' : userId,
'deliverId' : deliverId,
'restaurantId' : restaurantId,
'orderItems' : jsonEncode(orderItems),
'total' : total,
'orderStatus' : orderStatus
};
}
}
OrderItem class
class OrderItem{
RestaurantModel restaurant;
List<OrderProduct> products;
String id;
OrderItem({
required this.restaurant,
required this.products,
required this.id
});
Map<String, dynamic> toJson(){
return {
'restaurant' : restaurant.toJson(),
'products' : jsonEncode(products),
'id' : id,
};
}
}
RestaurantModel class
class RestaurantModel {
String uid;
String restaurantName;
String restaurantAddress;
String restaurantUrl;
String restaurantSlogan;
int stars;
String cost;
String category;
String status;
DateTime startDate;
List<Product>? products;
RestaurantModel({
required this.uid,
required this.restaurantName,
required this.restaurantAddress,
required this.restaurantSlogan,
required this.restaurantUrl,
required this.stars,
required this.cost,
required this.category,
required this.status,
required this.startDate,
this.products,
});
Map<String, Object?> toJson(){
return{
'restaurantName' : restaurantName,
'restaurantAddress' : restaurantAddress,
'restaurantSlogan' : restaurantSlogan,
'restaurantUrl': restaurantUrl,
'stars' : stars,
'cost' : cost,
'category' : category,
'status' : status,
'startDate' : startDate,
};
}
}
OrderProduct class
class OrderProduct{
Product product;
int quantity;
OrderProduct({
required this.product,
required this.quantity,
});
Map<String, dynamic> toJson(){
return {
'product' : product.toJson(),
'quantity' : quantity,
};
}
}
Product class
class Product{
String productId;
String productName;
String productDescription;
double productPrice;
String productUrl;
int productLikes;
String productUnit;
Product({
required this.productId,
required this.productName,
required this.productDescription,
required this.productPrice,
required this.productUrl,
required this.productLikes,
required this.productUnit,
}
);
Map<String, dynamic> toJson(){
return {
'productId' : productId,
'productName' : productName,
'productDescription' : productDescription,
'productPrice' : productPrice,
'productUrl' : productUrl,
'productLikes' : productLikes,
'productUnit' : productUnit,
};
}
}
So basically I'm getting an error when trying to call toJson() method from order.
void addOrderAsync(String userId, Order order) async{
// here is where im getting the error
final jsonData = order.toJson();
final response = await http.post(Uri.parse("$apiUrl/users/$userId/cart/add"),
headers: <String, String> {
'Content-Type': 'application/json; charset=UTF-8',
},
body: jsonEncode(jsonData),
);
if(response.statusCode == 200 || response.statusCode == 201){
// do something
}
else{
throw Exception("Failed to create user");
}
}
try change toJson() to:
Map<String, dynamic> toJson(){
final Map<String, dynamic> data = new Map<String, dynamic>();
data['productId'] = this.productId;
data['productName'] = this.productName;
data['productDescription'] = this.productDescription;
data['productPrice'] = this.productPrice;
data['productUrl'] = this.productUrl;
data['productLikes'] = this.productLikes;
data['productUnit'] = this.productUnit;
return data;
}
Try this:
Map<String, dynamic> toJson(){
return {
'id' : id,
'userId' : userId,
'deliverId' : deliverId,
'restaurantId' : restaurantId,
'orderItems' : orderItems.toJson(),
'total' : total,
'orderStatus' : orderStatus
};
}
Replace jsonEncode by toJson()
I am trying to work with firebase database from flutter. I have made a model class which I am converting to json and from json via plugin json_serializable. Where model class works perfectly fine with hard coded json data but when I am trying to save the encoded data to firebase database it's getting saved as a string instead of key value pair in firebase database.Below is my code to convert it and save it
List<Action> actions = [];
actions.add(new Action('This is label', 'mranuran.com'));
EgluCard egluCard = new EgluCard(true, true, "HI", "World", "Awesome",CardType.TYPE_1 , ["images"], 123, 125, "#FFFFFF", PlatformType.IOS, actions);
//print(json.encode(egluCard));
// var jsonString = '{"isInternal":true,"isPublished":true,"title":"HI","body":"World","caption":"Awesome","cardType":"TYPE_1","images":["images"],"expiry":123,"showAt":125,"bgColor":"#FFFFFF","platformType":"IOS","actions":[{"label":"This is label","url":"mranuran.com"}]}';
// Map<String,dynamic> cardMap = json.decode(jsonString);
// EgluCard egluCard = EgluCard.fromJson(cardMap);
// print(egluCard.actions[0].label);
var jsonString = json.encode(egluCard);
var trimmedString = jsonString.substring(0,jsonString.length);
print(trimmedString);
cardsDBRef.push().set(jsonString)
.then((_){
print('saved!!');
});
when I am printing the json.encode(eGluCard) then it's printing a valid json but when it's getting saved into firebase I am getting the following from firebase. It was supposed to save as key value pair but it was saved as a whole string.
"{\"isInternal\":true,\"isPublished\":true,\"title\":\"HI\",\"body\":\"World\",\"caption\":\"Awesome\",\"cardType\":\"TYPE_1\",\"images\":[\"images\"],\"expiry\":123,\"showAt\":125,\"bgColor\":\"#FFFFFF\",\"platformType\":\"IOS\",\"actions\":[{\"label\":\"This is label\",\"url\":\"mranuran.com\"}]}"
what can be wrong in this approach? below are my model classed and their generated serializer respectively
EgluCard.dart
import 'card_type.dart';
import 'platform_type.dart';
import 'action.dart';
import 'package:json_annotation/json_annotation.dart';
part 'eglu_card.g.dart';
#JsonSerializable()
class EgluCard {
bool isInternal;
bool isPublished;
String title;
String body;
String caption;
CardType cardType;
List<String> images;
int expiry;
int showAt;
String bgColor;
PlatformType platformType;
List<Action> actions;
EgluCard(this.isInternal,this.isPublished,this.title,this.body,this.caption,this.cardType,this.images,
this.expiry,this.showAt,this.bgColor,this.platformType,this.actions);
factory EgluCard.fromJson(Map<String, dynamic> json) => _$EgluCardFromJson(json);
Map<String, dynamic> toJson() => _$EgluCardToJson(this);
}
EgluCard Serializer
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'eglu_card.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
EgluCard _$EgluCardFromJson(Map<String, dynamic> json) {
return EgluCard(
json['isInternal'] as bool,
json['isPublished'] as bool,
json['title'] as String,
json['body'] as String,
json['caption'] as String,
_$enumDecodeNullable(_$CardTypeEnumMap, json['cardType']),
(json['images'] as List)?.map((e) => e as String)?.toList(),
json['expiry'] as int,
json['showAt'] as int,
json['bgColor'] as String,
_$enumDecodeNullable(_$PlatformTypeEnumMap, json['platformType']),
(json['actions'] as List)
?.map((e) =>
e == null ? null : Action.fromJson(e as Map<String, dynamic>))
?.toList());
}
Map<String, dynamic> _$EgluCardToJson(EgluCard instance) => <String, dynamic>{
'isInternal': instance.isInternal,
'isPublished': instance.isPublished,
'title': instance.title,
'body': instance.body,
'caption': instance.caption,
'cardType': _$CardTypeEnumMap[instance.cardType],
'images': instance.images,
'expiry': instance.expiry,
'showAt': instance.showAt,
'bgColor': instance.bgColor,
'platformType': _$PlatformTypeEnumMap[instance.platformType],
'actions': instance.actions
};
T _$enumDecode<T>(Map<T, dynamic> enumValues, dynamic source) {
if (source == null) {
throw ArgumentError('A value must be provided. Supported values: '
'${enumValues.values.join(', ')}');
}
return enumValues.entries
.singleWhere((e) => e.value == source,
orElse: () => throw ArgumentError(
'`$source` is not one of the supported values: '
'${enumValues.values.join(', ')}'))
.key;
}
T _$enumDecodeNullable<T>(Map<T, dynamic> enumValues, dynamic source) {
if (source == null) {
return null;
}
return _$enumDecode<T>(enumValues, source);
}
const _$CardTypeEnumMap = <CardType, dynamic>{CardType.TYPE_1: 'TYPE_1'};
const _$PlatformTypeEnumMap = <PlatformType, dynamic>{
PlatformType.ANDROID: 'ANDROID',
PlatformType.IOS: 'IOS',
PlatformType.ANDROID_THING: 'ANDROID_THING',
PlatformType.ANY: 'ANY'
};
Action.dart
import 'package:json_annotation/json_annotation.dart';
part 'action.g.dart';
#JsonSerializable()
class Action {
String label;
String url;
Action(this.label,this.url);
factory Action.fromJson(Map<String, dynamic> json) => _$ActionFromJson(json);
Map<String, dynamic> toJson() => _$ActionToJson(this);
}
Action Serializer
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'action.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
Action _$ActionFromJson(Map<String, dynamic> json) {
return Action(json['label'] as String, json['url'] as String);
}
Map<String, dynamic> _$ActionToJson(Action instance) =>
<String, dynamic>{'label': instance.label, 'url': instance.url};
PlatformType and CardType are enums
Okay turns out I have to decode and encoded string before passing it to firebase.
So code to save the model class to firebase will be like this:
List<Action> actions = [];
actions.add(new Action('This is label', 'mranuran.com'));
EgluCard egluCard = new EgluCard(true, true, "HI", "World", "Awesome",CardType.TYPE_1 , ["images"], 123, 125, "#FFFFFF", PlatformType.IOS, actions);
var jsonString = json.encode(egluCard);
print(json.decode(jsonString));
cardsDBRef.push().set(json.decode(jsonString))
.then((_){
print('saved!!');
});