I have class "DilemmData" which I need to save:
class DilemmData {
double percent = 0;
final String title;
final String date;
List<DilemmItemData> plus = [];
List<DilemmItemData> minus = [];
DilemmData(
plus,
minus, {
this.percent = 0,
this.title = '',
this.date = '',
});
static Map<String, dynamic> toJson(DilemmData dilemm) {
return {
'percent': dilemm.percent,
'title': dilemm.title,
'date': dilemm.date,
'plus': dilemm.plus.map((e) => e.toJson()).toList(),
'minus': dilemm.minus.map((e) => e.toJson()).toList(),
};
}
factory DilemmData.fromJson(Map<String, dynamic> json) {
return DilemmData(
json['plus'],
json['minus'],
percent: json['percent'],
title: json['title'],
date: json['date'],
);
}
static String encode(List<DilemmData> pressure) => json.encode(
pressure
.map<Map<String, dynamic>>((dil) => DilemmData.toJson(dil))
.toList(),
);
static List<DilemmData> decode(String dilemm) =>
((json.decode(dilemm) ?? []) as List<dynamic>)
.map<DilemmData>((dil) => DilemmData.fromJson(dil))
.toList();
}
class DilemmItemData {
final int importance;
final String argument;
DilemmItemData({this.importance = 0, this.argument = ''});
Map<String, dynamic> toJson() {
return {
'importance': importance,
'argument': argument,
};
}
factory DilemmItemData.fromJson(Map<String, dynamic> json) {
return DilemmItemData(
importance: json['importance'], argument: json['argument']);
}
}
There is save function:
DilemmData dilemm = DilemmData(
percent: 0,
title: controller.text,
date: clockString);
SharedPreferences sharedPreferences =
await SharedPreferences.getInstance();
String data = jsonEncode(dilemm);
sharedPreferences.setString('dilemms', data);
But when i try to save i get this error: JsonUnsupportedObjectError (Converting object to an encodable object failed: Instance of 'DilemmData'). Does anyone know how to save?
StackOverflow says I have a lot of code, but I don't know what else to write, I'll write random letters for this: shdjfhjjsdfjhwehfwouiehuwefuwefuwheugweghuweghuiweghuwueghuweweugihwueighuwhguwhgu
Here is the function to get the data:
Future loadDillems() async {
SharedPreferences sharedPreferences = await
SharedPreferences.getInstance();
if (sharedPreferences.containsKey('dilemms')) {
Map<String, dynamic> data =
jsonDecode(sharedPreferences.getString('dilemms')!);
MyApp.dilemmList = DilemmData.fromJson(data) as List<DilemmData>;
}
}
When converting the "top" class using its toJson() method, make sure that the subsequent classes' toJson() methods is also called. As such:
'plus': dilemm.plus.map((e) => e.toJson()).toList(),
And you of course have to implement toJson() and fromJson() in DilemmItemData as well.
Edit:
Okey, so a couple of alternatives. First of all, you had to create the new toJson() (and soon also fromJson()) methods. That is good.
As #Ivo wrote, if you pass the object to jsonEncode as you do now, then the methods cannot be static. But you could also pass DilemmData.toJson(dilemm) as:
String data = jsonEncode(DilemmData.toJson(dilemm));
But I'd recommend as #Ivo wrote to make it non-static, as you did with the new toJson method, and of course keep the toJson in DilemmItemData, and I suggest that you write the fromJson as well...
Second edit:
Your fromJson have to be a bit sharper. Something like this:
DilemmData(
(json['plus'] as List<dynamic>)
.map((e) => DilemmItemData.fromJson(e as Map<String, dynamic>))
.toList(),
Edit 3:
You are saving one DilemmData, so you have to read it as one (1) DilemmData. Remove the as List<DilemmData>; It is not all of a sudden a List when it is one object that you save (String data = jsonEncode(dilemm);)
So do as follows:
final oneDilemmData = DilemmData.fromJson(data);
I think you need to make your toJson() non static like this:
Map<String, dynamic> toJson() {
return {
'percent': percent,
'title': title,
'date': date,
'plus': plus,
'minus': minus,
};
}
your encode could be like this then:
static String encode(List<DilemmData> pressure) => json.encode(
pressure
.map<Map<String, dynamic>>((dil) => dil.toJson())
.toList(),
);
Related
I have a class "DilemmData" whose variables are loaded with data like this:
if (prefs.containsKey('dilemms')) {
MyApp.dilemmList = DilemmData.decode(prefs.getString('dilemms')!);
}
Here is the class:
class DilemmData {
double percent;
final String title;
final String date;
final List<DilemmItemData> plus = [];
final List<DilemmItemData> minus = [];
DilemmData({
plus,
minus,
this.percent = 0,
this.title = '',
this.date = '',
});
static Map<String, dynamic> toJson(DilemmData dilemm) => {
'percent': dilemm.percent,
'title': dilemm.title,
'date': dilemm.date,
'plus': dilemm.plus.map((e) => e.toJson()).toList(),
'minus': dilemm.minus.map((e) => e.toJson()).toList(),
};
factory DilemmData.fromJson(Map<String, dynamic> json) {
print('BOBA: ${json['plus']}');
return DilemmData(
plus: json['plus'],
minus: json['minus'],
percent: json['percent'],
title: json['title'],
date: json['date'],
);
}
static String encode(List<DilemmData> dilemm) => json.encode(
dilemm
.map<Map<String, dynamic>>((dil) => DilemmData.toJson(dil))
.toList(),
);
static List<DilemmData> decode(String dilemm) =>
(json.decode(dilemm) as List<dynamic>)
.map<DilemmData>((dil) => DilemmData.fromJson(dil))
.toList();
}
class DilemmItemData {
final int importance;
final String argument;
DilemmItemData({this.importance = 0, this.argument = ''});
Map<String, dynamic> toJson() {
return {
'importance': importance,
'argument': argument,
};
}
factory DilemmItemData.fromJson(Map<String, dynamic> json) {
return DilemmItemData(
importance: json['importance'], argument: json['argument']);
}
static List<DilemmItemData> decode(String item) =>
(json.decode(item) as List<dynamic>)
.map<DilemmItemData>((dil) => DilemmItemData.fromJson(dil))
.toList();
}
But the plus and minus variables are always empty. Does anyone know how to fix this?
The following code snippet would do the trick. Converting a DilemmItemData from JSON was missing.
factory DilemmData.fromJson(Map<String, dynamic> json) {
return DilemmData(
plus: (json['plus'] as List)
.map((json) => DilemmItemData.fromJson(json))
.toList(),
minus: (json['minus'] as List)
.map((json) => DilemmItemData.fromJson(json))
.toList(),
percent: json['percent'],
title: json['title'],
date: json['date'],
);
}
I am trying to convert a list of objects as a json string in shared preferences.
Object class
SuggestionModel suggestionModelFromJson(String str) =>
SuggestionModel.fromJson(json.decode(str));
String suggestionModelToJson(SuggestionModel data) =>
json.encode(data.toJson());
class SuggestionModel {
SuggestionModel({
this.category,
this.icon,
this.subs,
});
eCategory? category;
IconData? icon;
List<Sub>? subs;
factory SuggestionModel.fromJson(Map<String, dynamic> json) =>
SuggestionModel(
category: json["category"],
icon: json["icon"],
subs: List<Sub>.from(json["subs"].map((x) => Sub.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"category": category,
"icon": icon,
"subs": List<dynamic>.from(subs!.map((x) => x.toJson())),
};
}
class Sub {
Sub({
this.subCategory,
this.values,
});
String? subCategory;
List<Value>? values;
factory Sub.fromJson(Map<String, dynamic> json) => Sub(
subCategory: json["sub_category"],
values: List<Value>.from(json["values"].map((x) => Value.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"sub_category": subCategory,
"values": List<dynamic>.from(values!.map((x) => x.toJson())),
};
}
class Value {
Value({
this.subName,
this.selected,
});
String? subName;
bool? selected;
factory Value.fromJson(Map<String, dynamic> json) => Value(
subName: json["sub_name"],
selected: json["selected"],
);
Map<String, dynamic> toJson() => {
"sub_name": subName,
"selected": selected,
};
}
When I try to do
List<SuggestionModel> list;
String encodedData = jsonEncode(list);
it gives me an error
Converting object to an encodable object failed: Instance of 'SuggestionModel'
Im not following where the exact issue comes from. tried debugging and still no luck
How can I rectify this?
Update. I've changed the enum to a String and removed the IconData field. And the above issue had resolved.
Now when I try to get the saved Json string and convert that back to list of objects. I get an error
Unhandled Exception: type 'List<dynamic>' is not a subtype of type 'List<SuggestionModel>'
at this line
var t = await _dataManager.getSelectedList(s);
var addedObj = json.decode(json.decode(t!));
//here...
var list = addedObj.map((e) => SuggestionModel.fromJson(e)).toList();
Try this:
String encodedData = jsonEncode(list.map((e) => e.toJson()).toList());
So the first thing was to update the enum property of Model class to String and remove IconData.
Then for the second issue.
update the decoding function like
List<SuggestionModel> list =
addedObj.map((e) => SuggestionModel.fromJson(e)).toList();
i want to use for loop i need "photoThumbnailImagePath" array but i am not able to work on it...! i am trying to get array index of image path but i getting only one image.....! my value is not printing ! i gave u my code and my json data...! plz show me how it works how should i print my image value
if (response.statusCode == 200) {
var jsonResponse = json.decode(response.body);
print("laavvvvvvvvv :" + jsonResponse.toString());
var azim = List<FolderList>.from(jsonResponse["FolderList"].map((x) => FolderList.fromJson(x)));
// ignore: unnecessary_statements
print("printing");
for (final cam in azim){
print("photoThumbnailImagePath:" + cam.photoList[0].photoThumbnailImagePath.toString()); //i am getting here first image only i want all alisting array how
Photlistinng = [cam.photoList[0].photoThumbnailImagePath];
print("Photlistinng : " + Photlistinng.toString());
};
return AllPhotoListing.fromJson(json.decode(response.body));
} else {
// If the server did not return a 201 CREATED response,
// then throw an exception.
throw Exception('Failed to load data');
}
this my my code when api succesful then i use for loop but something wrong with my code so plz check
here is my json data converter
import 'dart:convert';
AllPhotoListing allPhotoListingFromJson(String str) => AllPhotoListing.fromJson(json.decode(str));
String allPhotoListingToJson(AllPhotoListing data) => json.encode(data.toJson());
class AllPhotoListing {
AllPhotoListing({
this.successCode,
this.successMessage,
this.totalPhotos,
this.totalLikes,
this.totalComments,
this.totalShared,
this.totalSelectedPhotosForAlbum,
this.watermarkType,
this.watermarkLogo,
this.watermarkText,
this.watermarkFont,
this.watermarkFontColor,
this.watermarkScaleHeight,
this.watermarkScaleWidth,
this.watermarkOpacity,
this.watermarkFontSize,
this.watermarkPlacement,
this.folderList,
});
String successCode;
String successMessage;
int totalPhotos;
int totalLikes;
int totalComments;
int totalShared;
int totalSelectedPhotosForAlbum;
String watermarkType;
String watermarkLogo;
String watermarkText;
String watermarkFont;
String watermarkFontColor;
int watermarkScaleHeight;
int watermarkScaleWidth;
double watermarkOpacity;
int watermarkFontSize;
String watermarkPlacement;
List<FolderList> folderList;
factory AllPhotoListing.fromJson(Map<String, dynamic> json) => AllPhotoListing(
successCode: json["SuccessCode"],
successMessage: json["SuccessMessage"],
totalPhotos: json["TotalPhotos"],
totalLikes: json["TotalLikes"],
totalComments: json["TotalComments"],
totalShared: json["TotalShared"],
totalSelectedPhotosForAlbum: json["TotalSelectedPhotosForAlbum"],
watermarkType: json["WatermarkType"],
watermarkLogo: json["WatermarkLogo"],
watermarkText: json["WatermarkText"],
watermarkFont: json["WatermarkFont"],
watermarkFontColor: json["WatermarkFontColor"],
watermarkScaleHeight: json["WatermarkScaleHeight"],
watermarkScaleWidth: json["WatermarkScaleWidth"],
watermarkOpacity: json["WatermarkOpacity"].toDouble(),
watermarkFontSize: json["WatermarkFontSize"],
watermarkPlacement: json["WatermarkPlacement"],
folderList: List<FolderList>.from(json["FolderList"].map((x) => FolderList.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"SuccessCode": successCode,
"SuccessMessage": successMessage,
"TotalPhotos": totalPhotos,
"TotalLikes": totalLikes,
"TotalComments": totalComments,
"TotalShared": totalShared,
"TotalSelectedPhotosForAlbum": totalSelectedPhotosForAlbum,
"WatermarkType": watermarkType,
"WatermarkLogo": watermarkLogo,
"WatermarkText": watermarkText,
"WatermarkFont": watermarkFont,
"WatermarkFontColor": watermarkFontColor,
"WatermarkScaleHeight": watermarkScaleHeight,
"WatermarkScaleWidth": watermarkScaleWidth,
"WatermarkOpacity": watermarkOpacity,
"WatermarkFontSize": watermarkFontSize,
"WatermarkPlacement": watermarkPlacement,
"FolderList": List<dynamic>.from(folderList.map((x) => x.toJson())),
};
}
class FolderList {
FolderList({
this.folderId,
this.title,
this.totalCount,
this.photoList,
});
int folderId;
String title;
int totalCount;
List<PhotoList> photoList;
factory FolderList.fromJson(Map<String, dynamic> json) => FolderList(
folderId: json["FolderId"],
title: json["Title"],
totalCount: json["TotalCount"],
photoList: List<PhotoList>.from(json["PhotoList"].map((x) => PhotoList.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"FolderId": folderId,
"Title": title,
"TotalCount": totalCount,
"PhotoList": List<dynamic>.from(photoList.map((x) => x.toJson())),
};
}
class PhotoList {
PhotoList({
this.photoId,
this.photoMainImagePath,
this.photoThumbnailImagePath, // i need this array in my api call
this.photoPreviewImagePath,
this.isSelectedPhoto,
this.isLikedPhoto,
this.photoSelectedCustomers,
this.photoSelectedPhotographerProfile,
});
int photoId;
String photoMainImagePath;
String photoThumbnailImagePath;
String photoPreviewImagePath;
int isSelectedPhoto;
int isLikedPhoto;
List<PhotoSelectedCustomer> photoSelectedCustomers;
String photoSelectedPhotographerProfile;
factory PhotoList.fromJson(Map<String, dynamic> json) => PhotoList(
photoId: json["PhotoId"],
photoMainImagePath: json["PhotoMainImagePath"],
photoThumbnailImagePath: json["PhotoThumbnailImagePath"],
photoPreviewImagePath: json["PhotoPreviewImagePath"],
isSelectedPhoto: json["IsSelectedPhoto"],
isLikedPhoto: json["IsLikedPhoto"],
photoSelectedCustomers: List<PhotoSelectedCustomer>.from(json["PhotoSelectedCustomers"].map((x) =>
PhotoSelectedCustomer.fromJson(x))),
photoSelectedPhotographerProfile: json["PhotoSelectedPhotographerProfile"],
);
Map<String, dynamic> toJson() => {
"PhotoId": photoId,
"PhotoMainImagePath": photoMainImagePath,
"PhotoThumbnailImagePath": photoThumbnailImagePath,
"PhotoPreviewImagePath": photoPreviewImagePath,
"IsSelectedPhoto": isSelectedPhoto,
"IsLikedPhoto": isLikedPhoto,
"PhotoSelectedCustomers": List<dynamic>.from(photoSelectedCustomers.map((x) => x.toJson())),
"PhotoSelectedPhotographerProfile": photoSelectedPhotographerProfile,
};
}
class PhotoSelectedCustomer {
PhotoSelectedCustomer({
this.profilePicture,
});
String profilePicture;
factory PhotoSelectedCustomer.fromJson(Map<String, dynamic> json) => PhotoSelectedCustomer(
profilePicture: json["ProfilePicture"],
);
Map<String, dynamic> toJson() => {
"ProfilePicture": profilePicture,
};
}
you can try this :
for(int i=0; i<azim.length; i++){
//print here
}
In my flutter app , I have 5 parameters for a building Like eleveator,storeroom,parking,buildAge,rentPriceThe default value of these parameters is 0 at the beginning ,I want to update every value in this ApartemanRentOptionModel class in different steps without changing other values and finally send complete values to the server.
I have a class for Rent Apartemans Options Like This :
class ApartemanRentOptionModel {
ApartemanRentOptionModel({
this.eleveator,
this.storeroom,
this.parking,
this.buildAge,
this.rentPrice
});
bool eleveator;
bool storeroom;
bool parking;
List<BuildAge> buildAge;
List<RentPrice> rentPrice;
factory ApartemanRentOptionModel.fromJson(Map<String, dynamic> json) => ApartemanRentOptionModel(
eleveator: json["eleveator"],
storeroom: json["storeroom"],
parking: json["parking"],
buildAge: List<BuildAge>.from(json["buildAge"].map((x) => BuildAge.fromJson(x))),
rentPrice: List<RentPrice>.from(json["rentPrice"].map((x) => RentPrice.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"eleveator": eleveator,
"storeroom": storeroom,
"parking": parking,
"buildAge": List<dynamic>.from(buildAge.map((x) => x.toJson())),
"rentPrice": List<dynamic>.from(rentPrice.map((x) => x.toJson())),
};
}
class BuildAge {
BuildAge({
this.buildAgeId,
this.buildAgeTitle,
this.buildAgeValue,
});
String buildAgeId;
String buildAgeTitle;
int buildAgeValue;
factory BuildAge.fromJson(Map<String, dynamic> json) => BuildAge(
buildAgeId: json["buildAgeID"],
buildAgeTitle: json["buildAgeTitle"],
buildAgeValue: json["buildAgeValue"],
);
Map<String, dynamic> toJson() => {
"buildAgeID": buildAgeId,
"buildAgeTitle": buildAgeTitle,
"buildAgeValue": buildAgeValue,
};
}
class RentPrice {
RentPrice({
this.rentPriceId,
this.rentPriceTitle,
this.rentPriceValue,
});
String rentPriceId;
String rentPriceTitle;
double rentPriceValue;
factory RentPrice.fromJson(Map<String, dynamic> json) => RentPrice(
rentPriceId: json["rentPriceID"],
rentPriceTitle: json["rentPriceTitle"],
rentPriceValue: json["rentPriceValue"].toDouble(),
);
Map<String, dynamic> toJson() => {
"rentPriceID": rentPriceId,
"rentPriceTitle": rentPriceTitle,
"rentPriceValue": rentPriceValue,
};
}
i need to change value in some data like BuildAge or RentPrice with a function like this :
ApartemanRentOptionModel _currentApartemanData;
changeCurretAparemanData(newdata) {
_currentApartemanData.toJson().update("BuildAge", (value) => newdata)
notifyListeners();
return null;
}
But it not work and nothing changes , Please help me how to update different values of a single Model class in several time . Thank you
You can use getter or setter function in model .getter function use for get value from model and setter use for set or update value in model.
I want to convert a list of 'Box' objects to a json file and also read it back in (json file to a list a 'Box' objects), but I'm a bit stuck on the implementation. I have written the below code, but I can only write a single 'Box' object to the json and convert a single 'Box' object back. When I try to do this with a list I hit errors like data that gets overwritten or just a single object that gets returned.
So in short, I want to write a List to json and convert json to List
I have the following data structure
Box model
class Box {
final String nameBox;
final List<Item> items;
Box({#required this.nameBox, #required this.items});
factory Box.fromJson(Map<String, dynamic> json) {
var items = json['items'];
List<Item> itemsList = items.cast<Item>();
return new Box(
nameBox: json["nameBox"],
items: itemsList
);
}
Map<String, dynamic> toJson() => {
"nameBox": nameBox,
"items": items,
};
}
Box fromJson(String boxData) {
return Box.fromJson(json.decode(boxData));
}
String toJson(Box box) {
return json.encode(box.toJson());
}
Item model
class Item {
final String itemName;
final int quantity;
Item({#required this.itemName, #required this.quantity});
factory Item.fromJson(Map<String, dynamic> json) {
return new Item(itemName: json["itemName"], quantity: json["quantity"]);
}
Map<String, dynamic> toJson() => {
"itemName": itemName,
"quantity": quantity,
};
}
Item fromJson(String itemData) {
return Item.fromJson(json.decode(itemData));
}
String toJson(Item item) {
return json.encode(item.toJson());
}
writeToJson function
Future writeJson(Box box) async {
final file = await _localFile;
List<Box> tempRead = await returnBoxes();
if (tempRead.isEmpty || tempRead == null) {
return;
}
tempRead.add(box);
file.writeAsString(json.encode(tempRead));
}
readJson function
Future<List<Box>> returnBoxes() async {
final file = await _localFile;
List<Box> boxList = new List<Box>();
Map<String, dynamic> content = await json.decode(file.readAsStringSync());
boxList.add(Box.fromJson(content));
return boxList;
}
I also tried to cast the json content to a list, but then I hit some iterable errors. Any who can help me out?
JSON has this idiosyncrasy that everything is either an object or an array, and you don't know what you get until you decode it. Dart decodes the two json types into a Map<String, dynamic> and List<dynamic> respectively. (The reason that you get dynamic is because each of them could itself then be a value, a json array or a json object, recursively.)
Dart encodes a Dart object by calling toJson on it and a Dart list by emitting a [ then each member of the list then a ].
Knowing that, it's easy to encode and decode arrays/lists. (I removed all the unnecessary code.)
class Box {
final String nameBox;
final List<Item> items;
Box({#required this.nameBox, #required this.items});
factory Box.fromJson(Map<String, dynamic> json) => Box(
nameBox: json['nameBox'],
items: json['items'].map<Item>((e) => Item.fromJson(e)).toList(),
);
Map<String, dynamic> toJson() => {
'nameBox': nameBox,
'items': items,
};
}
class Item {
final String itemName;
final int quantity;
Item({#required this.itemName, #required this.quantity});
factory Item.fromJson(Map<String, dynamic> json) => Item(
itemName: json['itemName'],
quantity: json['quantity'],
);
Map<String, dynamic> toJson() => {
'itemName': itemName,
'quantity': quantity,
};
}
Future writeJson(Box box) async {
final file = await _localFile;
var boxes = await returnBoxes();
/* I think you probably don't want this...
if (boxes.isEmpty || boxes == null) {
return;
}*/
// but rather, this
if (boxes == null) boxes = [];
boxes.add(box);
await file.writeAsString(json.encode(boxes));
}
Future<List<Box>> returnBoxes() async {
final file = await _localFile;
// because the json is an array (i.e. enclosed in []) it will be decoded
// as a Dart List<dynamic>
List<dynamic> d = json.decode(await file.readAsString());
// here we map the List<dynamic> to a series of Box elements
// each dynamic is passed to the Box.fromJson constructor
// and the series is formed into a List by toList
return d.map<Box>((e) => Box.fromJson(e)).toList();
}