json - 无法使用 json 正文发布 http 请求,因为 'dart:convert' 包中的 jsonEncode 方法添加了转义字符
问题描述
我正在尝试使用带有 JSON 正文的 http/http.dart 包发出 http 发布请求。为此,我正在尝试使用 jsonEncode(dart:convert 包)将 Map 转换为 JSON,但无法这样做,因为 jsonEncode 在转换期间添加了转义字符,这使得 JSON 字符串成为无效的 JSON。
Future postData(Map data) async {
Map<String, String> headers = {"Content-type": "application/json"};
var body = jsonEncode(data);
http.Response response = await http.post(url, headers: headers, body: body);
if (response.statusCode == 201) {
print("Customer creared");
} else {
print(response.statusCode);
}
}
当我调试上面的代码时,body 的值如下:
body = {\"first_name\":\"Manish\",\"last_name\":\"Kumar\",\"phone_numebr\":\"9123456789\",\"seal\":\"manne\"}
所以在这里我可以看到一个额外的转义字符被添加到 json 字符串中,这使得很难使用 json 正文进行 http post 请求。
我尝试通过直接放置此字符串来发出 http post 请求,并且效果很好。下面的代码:
http.Response response = await http.post(url, headers: headers, body: '{"first_name":"Manish","last_name":"Kumar","phone_numebr":"9123456789","seal":"manne"}');
有人可以帮我将地图转换为没有转义字符的 json 吗?
解决方案
最后我得到了答案。
我创建了一个 dataTest 变量,如下所示:
final dataTest = {
'first_name': firstName,
'last_name': lastName,
'seal': seal,
'phone_number': phoneNumber
};
这里 firstName、lastName、seal 和 phoneNumber 是字符串类型。
现在打电话,
postData(dataTest);
Future postData(dynamic data) async {
Map<String, String> headers = {"Content-type": "application/json"};
http.Response response = await http
.post(url, headers: headers, body: json.encode(data));
if (response.statusCode == 201) {
print("Customer creared");
} else {
print(response.statusCode);
}
}
所以这里的关键是在动态类型上调用json.encode方法,然后传递给http.post的body参数。