- r - 以节省内存的方式增长 data.frame
- ruby-on-rails - ruby/ruby on rails 内存泄漏检测
- android - 无法解析导入android.support.v7.app
- UNIX 域套接字与共享内存(映射文件)
您好,我有一个类,其中嵌套了其他类。我想将此对象转换为 JSON 字符串并将其发送到服务器。
我尝试了很多来自堆栈溢出和谷歌搜索的答案。不足以回答我的问题。
感谢大家的帮助。
这是我的模型
class Place {
String name;
String description;
List<PhoneNumber> phoneNumbers;
List<String> tags;
GPSCoordinante gpsCoordinates;
List<Service> services;
List<Album> albums;
SocialMedia socialMedia;
List<Comment> comments;
List<String> imageURLArray;
int rating;
int shares;
int favorites;
int views;
String category;
String subcategory;
WorkingHour workingHours;
bool deleted;
double distanceToUser;
bool isApproved;
String address;
List<String> coverImages;
Place({
this.name,
this.description,
this.phoneNumbers,
this.tags,
this.gpsCoordinates,
this.services,
this.albums,
this.socialMedia,
this.comments,
this.imageURLArray,
this.rating,
this.shares,
this.favorites,
this.views,
this.category,
this.subcategory,
this.workingHours,
this.deleted,
this.distanceToUser,
this.isApproved ,
this.address,
this.coverImages,
});
factory Place.fromJson(Map<String, dynamic> json) {
List phoneNumbersJsonList = json['phoneNumbers'] as List;
List<PhoneNumber> parsedPhoneNumbers = phoneNumbersJsonList.map((value) => PhoneNumber.fromJson(value)).toList();
List servicesJsonList = json['services'] as List;
List<Service> parsedServices = servicesJsonList.map((value) => Service.fromJson(value)).toList();
List walbumsJsonList = json['albums'] as List;
List<Album> parsedAlbums = walbumsJsonList.map((value) => Album.fromJson(value)).toList();
List commentsJsonList = json['comments'] as List;
List<Comment> parsedComments = commentsJsonList.map((value) => Comment.fromJson(value)).toList();
return Place(
name: json['name'],
description: json['description'],
phoneNumbers: parsedPhoneNumbers,
gpsCoordinates: json['gpsCoordinates'],
services: parsedServices,
albums: parsedAlbums,
socialMedia: json['socialMedia'],
comments: parsedComments,
imageURLArray: json['imageURLArray'],
rating: json['rating'],
shares : json['shares'],
favorites: json['favorites'],
category: json['category'],
subcategory: json['subcategory'],
workingHours: json['workingHours'],
deleted: json['deleted'],
isApproved: json['isApproved'],
address: json['address'],
coverImages: json['coverImages'],
);
}
Map toMap() {
var map = new Map<String, dynamic>();
map["name"] = name;
map["description"] = description;
map["services"] = services;
map["albums"] = albums;
map["comments"] = comments;
map["imageURLArray"] = imageURLArray;
map["rating"] = rating;
map["shares"] = shares;
map["favorites"] = favorites;
map["category"] = category;
map["subcategory"] = subcategory;
map["workingHours"] = workingHours;
map["deleted"] = deleted;
map["isApproved"] = isApproved;
map["address"] = address;
map["coverImages"] = coverImages;
return map;
}
}
class PhoneNumber {
int phoneNumber;
String owner;
PhoneNumber({
this.phoneNumber,
this.owner
});
factory PhoneNumber.fromJson(Map<String, dynamic> json) {
return PhoneNumber(
phoneNumber: json['phoneNumber'],
owner: json['owner'],
);
}
Map toMap() {
var map = new Map<String, dynamic>();
map["phoneNumber"] = phoneNumber;
map["owner"] = owner;
return map;
}
}
class GPSCoordinante {
double longitude;
double latitude;
GPSCoordinante({
this.longitude,
this.latitude
});
factory GPSCoordinante.fromJson(Map<String, dynamic> json) {
return GPSCoordinante(
longitude: json['longitude'],
latitude: json['latitude'],
);
}
Map toMap() {
var map = new Map<String, dynamic>();
map["longitude"] = longitude;
map["latitude"] = latitude;
return map;
}
}
class Service {
String name;
String description;
Service({
this.name,
this.description
});
factory Service.fromJson(Map<String, dynamic> json) {
return Service(
name: json['name'],
description: json['description'],
);
}
Map toMap() {
var map = new Map<String, dynamic>();
map["name"] = name;
map["description"] = description;
return map;
}
}
class Album {
String name;
String nameEn;
List<Item> items;
bool isAutoConvertToUSDEnabled;
bool isAllItemsDeliveryEnabled;
Album({
this.name,
this.nameEn,
this.items,
this.isAutoConvertToUSDEnabled,
this.isAllItemsDeliveryEnabled
});
factory Album.fromJson(Map<String, dynamic> json) {
List itemsJsonList = json['items'] as List;
List<Item> parsedItems = itemsJsonList.map((value) => Item.fromJson(value)).toList();
return Album(
name: json['name'],
nameEn: json['nameEn'],
items: parsedItems,
isAutoConvertToUSDEnabled: json['isAutoConvertToUSDEnabled'],
isAllItemsDeliveryEnabled: json['isAllItemsDeliveryEnabled']
);
}
Map toMap() {
var map = new Map<String, dynamic>();
map["name"] = name;
map["nameEn"] = nameEn;
map["items"] = items;
map["isAutoConvertToUSDEnabled"] = isAutoConvertToUSDEnabled;
map["isAllItemsDeliveryEnabled"] = isAllItemsDeliveryEnabled;
return map;
}
}
class Item{
List<String> imageVariants;
String name;
String nameEn;
bool isAutoConvertNameToEnglishEnabled;
List<String> tags;
int priceIQD;
double priceUSD;
String description;
bool isDeliveryAvailable;
bool isDinarAutomaticallyConvertedToDollar;
int itemIndex;
int albumIndex;
bool isDeleted;
Item({
this.imageVariants,
this.name,
this.nameEn,
this.isAutoConvertNameToEnglishEnabled,
this.tags,
this.priceIQD,
this.priceUSD,
this.description,
this.isDeliveryAvailable,
this.isDinarAutomaticallyConvertedToDollar,
this.itemIndex,
this.albumIndex,
this.isDeleted
});
factory Item.fromJson(Map<String, dynamic> json) {
return Item(
imageVariants: json['imageVariants'],
name: json['name'],
nameEn: json['nameEn'],
isAutoConvertNameToEnglishEnabled: json['isAutoConvertNameToEnglishEnabled'],
tags: json['tags'],
priceIQD: json['priceIQD'],
priceUSD: json['priceUSD'],
description: json['description'],
isDeliveryAvailable: json['isDeliveryAvailable'],
isDinarAutomaticallyConvertedToDollar: json['isDinarAutomaticallyConvertedToDollar'],
albumIndex: json['albumIndex'],
itemIndex: json['itemIndex'],
isDeleted: json['isDeleted'],
);
}
Map toMap() {
var map = new Map<String, dynamic>();
map["imageVariants"] = imageVariants;
map["name"] = name;
map["nameEn"] = nameEn;
map["isAutoConvertNameToEnglishEnabled"] = isAutoConvertNameToEnglishEnabled;
map["tags"] = tags;
map["priceIQD"] = priceIQD;
map["priceUSD"] = priceUSD;
map["description"] = description;
map["isDeliveryAvailable"] = isDeliveryAvailable;
map["isDinarAutomaticallyConvertedToDollar"] = isDinarAutomaticallyConvertedToDollar;
map["albumIndex"] = albumIndex;
map["itemIndex"] = itemIndex;
map["isDeleted"] = isDeleted;
return map;
}
}
class Comment{
String user;
String userId;
String text;
DateTime dateTime;
Comment({
this.user,
this.userId,
this.text,
this.dateTime
});
factory Comment.fromJson(Map<String, dynamic> json) {
return Comment(
user: json['user'],
userId: json['userId'],
text: json['text'],
dateTime: json['dateTime'],
);
}
Map toMap() {
var map = new Map<String, dynamic>();
map["user"] = user;
map["userId"] = userId;
map["text"] = text;
map["dateTime"] = dateTime;
return map;
}
}
class WorkingHour{
String openingHour;
String openingHourAmOrPm;
String closingHour;
String closingHourAmOrPm;
WorkingHour({
this.openingHour,
this.openingHourAmOrPm,
this.closingHour,
this.closingHourAmOrPm
});
factory WorkingHour.fromJson(Map<String, dynamic> json) {
return WorkingHour(
openingHour: json['openingHour'],
openingHourAmOrPm: json['openingHourAmOrPm'],
closingHour: json['closingHour'],
closingHourAmOrPm: json['closingHourAmOrPm'],
);
}
Map toMap() {
var map = new Map<String, dynamic>();
map["openingHour"] = openingHour;
map["openingHourAmOrPm"] = openingHourAmOrPm;
map["closingHour"] = closingHour;
map["closingHourAmOrPm"] = closingHourAmOrPm;
return map;
}
}
class SocialMedia {
String facebook ;
String instagram;
String youTube;
String snapChat;
String twitter;
String googlePlus;
String pinterest;
SocialMedia({
this.facebook,
this.instagram,
this.youTube,
this.snapChat,
this.twitter,
this.googlePlus,
this.pinterest
});
factory SocialMedia.fromJson(Map<String, dynamic> json) {
return SocialMedia(
facebook: json['facebook'],
instagram: json['instagram'],
youTube: json['youTube'],
snapChat: json['snapChat'],
twitter: json['twitter'],
googlePlus: json['googlePlus'],
pinterest: json['pinterest'],
);
}
Map toMap() {
var map = new Map<String, dynamic>();
map["facebook"] = facebook;
map["instagram"] = instagram;
map["youTube"] = youTube;
map["twitter"] = twitter;
map["snapChat"] = snapChat;
map["googlePlus"] = googlePlus;
map["pinterest"] = pinterest;
return map;
}
}
我正在尝试将这个 Place 对象发送到服务器:
Place place = Place(
name: 'some name',
description: 'some description',
phoneNumbers: [PhoneNumber(phoneNumber: 125252525, owner: 'ali')],
tags: ['some tag 2', 'some tag 2'],
gpsCoordinates: GPSCoordinante(latitude: 11332, longitude: 13415),
services: [Service(name: 'some service', description: 'some description')],
albums: [
Album(
name: 'some album name',
nameEn: 'someEN name',
items: [
Item(
name: 'some item name',
imageVariants: ['a;lgjlagj', 'ag;ja;gj;ag'],
nameEn: 'some en name',
isAutoConvertNameToEnglishEnabled: true,
tags: ['aggagag'],
priceIQD: 32425,
priceUSD: 252525,
description: 'agkgl;aj g;g ja;g ',
isDeliveryAvailable: true,
isDinarAutomaticallyConvertedToDollar: true,
itemIndex: 1,
albumIndex: 2)
],
isAutoConvertToUSDEnabled: true,
isAllItemsDeliveryEnabled: false)
],
socialMedia: SocialMedia(facebook: 'facebook url'),
comments: [
Comment(
user: 'some user',
userId: '324-2-5-25',
text: 'some comment',
dateTime: DateTime.now())
],
imageURLArray: ['some url'],
rating: 0,
shares: 0,
favorites: 0,
views: 0,
category: 'sdagagasga;lgjaa;lgj',
subcategory: 'as;glgjasl;gjas;lgkj',
workingHours: WorkingHour(
openingHour: '11', openingHourAmOrPm: 'am', closingHour: '11:00'),
deleted: false,
distanceToUser: 225252,
isApproved: false,
address: "some adress",
coverImages: ['image one', 'image 2']);
我在使用 json.encode(place)
时总是出错;或 json.encode(place.toMap())
像这样
converting object to an encodable object failed: Instance of 'Service'
如何使这项工作?
最佳答案
看来您不需要编写那么多代码来将您的类编码和解码为 JSON 字符串。为避免大量冗余并让您的生活更轻松,请使用以下解决方案:
事情是这样的:
首先在你的 pubspec.yaml 中依赖这些库:
dependencies:
# Your other regular dependencies here
json_annotation: ^2.0.0
dev_dependencies:
# Your other dev_dependencies here
build_runner: ^1.0.0
json_serializable: ^2.0.0
然后在您拥有所有模型类的文件中,在顶部添加:
import 'package:json_annotation/json_annotation.dart';
part 'user.g.dart';
而不是 part 'user.g.dart';
中的 user 使用模型类所在的文件的名称。在我的例子中它是 model.dart 所以它变成:
part 'model.g.dart';
这给出了一条红色的波浪线:
这非常好,您需要做的是在项目根目录的 flutter 终端中运行以下命令:
flutter pub run build_runner watch
这样做是生成 part 'model.g.dart';
文件,这样您就不会再看到红色下划线了。它会监视您的模型(包含您的模型的文件,在我的例子中是 models.dart 文件),以了解您的类中变量或字段的任何更改。
如果您进行任何更改,它将自动重新生成模型与 JSON 之间的转换所需的代码,这意味着需要(json 解码和编码)。
然后您必须将此行添加到模型文件(在我的例子中为 models.dart)中的每个类的上方。
因此将此添加到每个类上方的行:
@JsonSerializable(explicitToJson: true)
例如像这样:
@JsonSerializable(explicitToJson: true)
class Place{ some fields};
并且在您的类定义中,您必须将此添加到每个类:
factory Place.fromJson(Map<String, dynamic> json) => _$PlaceFromJson(json);
Map<String, dynamic> toJson() => _$PlaceToJson(this);
当然,您必须将变量 _$PlaceFromJson(json)
和 _$PlaceToJson(this)
更改为能够反射(reflect)您的类名的内容。例如,如果我有一个 PhoneNumber 类,我必须将这些两个变量分别更改为 _$PhoneNumberFromJson(json)
和 _$PhoneNumberToJson(this)
。
现在您只需要创建一个模型对象,例如 Place 类,然后将其传递给 jsonEndcode 或 jsonDecode,如下所示:
放置地方 = 放置(名称:“某个名字”,描述:“一些描述”);
var placeEncoded = jsonEncode(place);
print(placeEncoded);
var placeDecoded = jsonDecode(place);
print(placeDecoded );
这就是您需要做的所有事情。
官方文档可以在这个页面找到: https://flutter.dev/docs/development/data-and-backend/json#code-generation
这是我的 model.dart 现在的样子:
import 'package:json_annotation/json_annotation.dart';
part 'models.g.dart';
@JsonSerializable(explicitToJson: true)
class Place {
String name;
String description;
List<PhoneNumber> phoneNumbers;
List<String> tags;
GPSCoordinante gpsCoordinates;
List<Service> services;
List<Album> albums;
SocialMedia socialMedia;
List<Comment> comments;
List<String> imageURLArray;
int rating;
int shares;
int favorites;
int views;
String category;
String subcategory;
WorkingHour workingHours;
bool deleted;
double distanceToUser;
bool isApproved;
String address;
List<String> coverImages;
Place({
this.name,
this.description,
this.phoneNumbers,
this.tags,
this.gpsCoordinates,
this.services,
this.albums,
this.socialMedia,
this.comments,
this.imageURLArray,
this.rating,
this.shares,
this.favorites,
this.views,
this.category,
this.subcategory,
this.workingHours,
this.deleted,
this.distanceToUser,
this.isApproved ,
this.address,
this.coverImages,
});
factory Place.fromJson(Map<String, dynamic> json) => _$PlaceFromJson(json);
Map<String, dynamic> toJson() => _$PlaceToJson(this);
}
@JsonSerializable(explicitToJson: true)
class PhoneNumber {
int phoneNumber;
String owner;
PhoneNumber({
this.phoneNumber,
this.owner
});
factory PhoneNumber.fromJson(Map<String, dynamic> json) => _$PhoneNumberFromJson(json);
Map<String, dynamic> toJson() => _$PhoneNumberToJson(this);
}
@JsonSerializable(explicitToJson: true)
class GPSCoordinante {
double longitude;
double latitude;
GPSCoordinante({
this.longitude,
this.latitude
});
factory GPSCoordinante.fromJson(Map<String, dynamic> json) => _$GPSCoordinanteFromJson(json);
Map<String, dynamic> toJson() => _$GPSCoordinanteToJson(this);
}
@JsonSerializable(explicitToJson: true)
class Service {
String name;
String description;
Service({
this.name,
this.description
});
factory Service.fromJson(Map<String, dynamic> json) => _$ServiceFromJson(json);
Map<String, dynamic> toJson() => _$ServiceToJson(this);
}
@JsonSerializable(explicitToJson: true)
class Album {
String name;
String nameEn;
List<Item> items;
bool isAutoConvertToUSDEnabled;
bool isAllItemsDeliveryEnabled;
Album({
this.name,
this.nameEn,
this.items,
this.isAutoConvertToUSDEnabled,
this.isAllItemsDeliveryEnabled
});
factory Album.fromJson(Map<String, dynamic> json) => _$AlbumFromJson(json);
Map<String, dynamic> toJson() => _$AlbumToJson(this);
}
@JsonSerializable(explicitToJson: true)
class Item{
List<String> imageVariants;
String name;
String nameEn;
bool isAutoConvertNameToEnglishEnabled;
List<String> tags;
int priceIQD;
double priceUSD;
String description;
bool isDeliveryAvailable;
bool isDinarAutomaticallyConvertedToDollar;
int itemIndex;
int albumIndex;
bool isDeleted;
Item({
this.imageVariants,
this.name,
this.nameEn,
this.isAutoConvertNameToEnglishEnabled,
this.tags,
this.priceIQD,
this.priceUSD,
this.description,
this.isDeliveryAvailable,
this.isDinarAutomaticallyConvertedToDollar,
this.itemIndex,
this.albumIndex,
this.isDeleted
});
factory Item.fromJson(Map<String, dynamic> json) => _$ItemFromJson(json);
Map<String, dynamic> toJson() => _$ItemToJson(this);
}
@JsonSerializable(explicitToJson: true)
class Comment{
String user;
String userId;
String text;
DateTime dateTime;
Comment({
this.user,
this.userId,
this.text,
this.dateTime
});
factory Comment.fromJson(Map<String, dynamic> json) => _$CommentFromJson(json);
Map<String, dynamic> toJson() => _$CommentToJson(this);
}
@JsonSerializable(explicitToJson: true)
class WorkingHour{
String openingHour;
String openingHourAmOrPm;
String closingHour;
String closingHourAmOrPm;
WorkingHour({
this.openingHour,
this.openingHourAmOrPm,
this.closingHour,
this.closingHourAmOrPm
});
factory WorkingHour.fromJson(Map<String, dynamic> json) => _$WorkingHourFromJson(json);
Map<String, dynamic> toJson() => _$WorkingHourToJson(this);
}
@JsonSerializable(explicitToJson: true)
class SocialMedia {
String facebook ;
String instagram;
String youTube;
String snapChat;
String twitter;
String googlePlus;
String pinterest;
SocialMedia({
this.facebook,
this.instagram,
this.youTube,
this.snapChat,
this.twitter,
this.googlePlus,
this.pinterest
});
factory SocialMedia.fromJson(Map<String, dynamic> json) => _$SocialMediaFromJson(json);
Map<String, dynamic> toJson() => _$SocialMediaToJson(this);
}
当不必要的代码被丢弃并且不再使用时,我喜欢它。这就是我真正喜欢 Flutter 的原因。
保重。
关于json - 如何将复杂(嵌套)对象解析为 JSON 并在 flutter 中使用 HTTP 将其发送到服务器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57662221/
我正在使用 voip 推送通知制作 ios 应用程序。 我想从 Node js 发送 voip 推送通知,但不是很好。 我阅读了本教程 CallKit iOS Swift Tutorial for V
我编写了一个服务器,当浏览器尝试连接到某些站点时,它会检查黑名单并发回 404,但是当我调用 send() 时没有错误,但消息不会出现在网络上浏览器,除非我关闭连接? 有什么建议吗? 接受来自浏览器的
#include int main() { char c = getchar(); //EOF (ctrl + d ) while( ( c = getchar() ) != '?'
我正在尝试使用MailMessage对象通过PowerShell发送电子邮件。该脚本使用Import-CSV来使用文件,然后在电子邮件正文中使用ConvertTo-HTML。由于我要发送的电子邮件客户
我需要创建一个脚本,每 30 秒对网络流量进行一次采样并存储发送/接收的字节。该数据随后用于绘制图形。我编写了一个在 Windows 2012 上完美运行的程序,但我意识到某些 cmdlet 在以前的
我正在运行“autoit3.chm”文件。当它运行时,我想发送一个向下键箭头,但它不起作用: $file = FileGetShortName("C:\Users\PHSD100-SIC\Deskto
当我使用网络浏览器测试我的程序时,我可以很好地写入套接字/FD,所以我决定循环它并在连接中途切断连接,我发现了一个问题。 send() 能够在套接字不可用时关闭整个程序。我认为问题在于该程序陷入了第
我正在运行“autoit3.chm”文件。当它运行时,我想发送一个向下键箭头,但它不起作用: $file = FileGetShortName("C:\Users\PHSD100-SIC\Deskto
所以我试图向自己发送数据并接收数据然后打印它,现在我已经测试了一段时间,我注意到它没有发送任何东西,事实上,也许它是,但我没有正确接收它,我需要这方面的帮助。 这就是我用来发送数据的
问题:开发人员创建自己的序列化格式有多常见?具体来说,我使用 java 本质上将对象作为一个巨大的字符串发送,并用标记来分隔变量。 我的逻辑:我选择这个是因为它几乎消除了语言依赖性(忽略java的修改
我必须在 Linux 上编写一个应用程序,该应用程序需要与具有自定义以太网类型的设备进行通信。甚至在如何编写这样的应用程序中也有很多解决方案。一个缺点是需要 root 访问权限(AFAIK)。之后释放
我有一个包含三个单选按钮选项的表单。我需要将表单数据提交到另一个文件,但由于某种原因,发送的数据包含所选单选按钮的值“on”,而不是 value 属性的值。 我尝试通过 post() 函数手动操作和发
基本上我想实现这样的目标: Process 1 Thread 1 Receive X from process 2 Thread 2 Receive Y from proces
我目前正在 Google App Engine 上开发一个系统,对它还很陌生,我正在使用 Java 平台进行开发。我在 servlet 之间发送 session 对象时遇到问题。我已经在 appeng
当我尝试将“this”(触发的元素)作为参数发送给函数时,函数收到“Object[Document build.php]”作为参数,而不是触发的元素。请让我知道我的错误: function set(a
我正在寻找让我的应用响应联系人 > 发送的魔法咒语。我希望能够接收联系人的 URI 以便检索联系人。谁有 list 过滤器/代码 fragment 吗? 最佳答案 我没有睾丸,但您可以尝试基于 ACT
关于我心爱的套接字的另一个问题。我先解释一下我的情况。之后我会告诉你是什么困扰着我。 我有一个客户端和一个服务器。这两个应用程序都是用 C++ 编写的,实现了 winsock2。连接通过 TCP 和
我看到了这篇文章 http://www.eskimo.com/~scs/cclass/int/sx5.html 但这部分让我感到困惑:如果我们已经使用 send_array 或 send_array_
我对这行代码有疑问。我必须将一个数据包带到一个端口并重新发送到接口(interface)(例如:eth0)。我的程序成功地从端口获取数据包,但是当我重新发送(使用 send())到接口(interfa
我正在尝试编写一个 X11 输入驱动程序,它可以使用我的 Android 手机上的触摸屏来移动和单击鼠标。我可以正常移动鼠标,但我无法让应用程序正确识别点击。我当前的代码位于 https://gist
我是一名优秀的程序员,十分优秀!