【发布时间】:2019-12-12 08:23:24
【问题描述】:
如何在 Flutter 中为这样的 json 制作 post 方法
{
"app_id": "3djdjkdjde",
"include_external_user_ids": ["88"],
"contents": {"en": "your order is created"}
}
当您在 json 中看到它的 json 我的内容问题时,它的值是 json
我用 post 方法制作了这个模型,但我不知道如何解析内容,你可以看到我现在将它的值设为 null
此时如果有静态消息的内容不需要动态值就可以了
import 'dart:async';
import 'dart:convert';
import 'package:http/http.dart' as http;
Notifications notificationsFromJson(String str) => Notifications.fromJson(json.decode(str));
String notificationsToJson(Notifications data) => json.encode(data.toJson());
class Notifications {
String appId;
List<String> includeExternalUserIds;
Contents contents;
Notifications({
this.appId,
this.includeExternalUserIds,
this.contents,
});
factory Notifications.fromJson(Map<String, dynamic> json) => new Notifications(
appId: json["app_id"],
includeExternalUserIds: new List<String>.from(json["include_external_user_ids"].map((x) => x)),
contents: Contents.fromJson(json["contents"]),
);
Map<String, dynamic> toJson() => {
"app_id": appId,
"include_external_user_ids": new List<dynamic>.from(includeExternalUserIds.map((x) => x)),
"contents": contents.toJson(),
};
static Future<bool> postNotification(serviceUri, notificationData) async {
var client = new http.Client();
bool result = false;
try {
final Map<String, String> _notificationData = {
'app_id': notificationData['app_id'].toString(),
'include_external_user_ids': orderData['include_external_user_ids'].toString(),
"contents": null,
};
await client.post(serviceUri,
body: json.encode(_notificationData),
headers: { 'Authorization' : 'Bearer ' + notificationData['Token'], "Content-Type": "application/json"}
)
.then((http.Response response) {
var responseModel = json.decode(response.body);
if(responseModel != null && responseModel['status'] == true) {
result = true;
} else {
result = false;
}
});
}
catch(e) {
result = false;
}
finally {
client.close();
}
return result;
}
}
class Contents {
String en;
Contents({
this.en,
});
factory Contents.fromJson(Map<String, dynamic> json) => new Contents(
en: json["en"],
);
Map<String, dynamic> toJson() => {
"en": en,
};
}
谢谢
【问题讨论】:
-
你应该使用httpflutter包
-
是的,我知道并且我构建了函数,但是我如何在 json 中为 json 发布帖子