Dart:将 Map 转换为 JSON 并引用所有元素

Dart: convert Map to JSON with all elements quoted

我正在将 Dart 中的表单序列化为 JSON,然后使用 Jackson 将其发布到 Spring MVC 后端以反序列化 JSON.

在 dart 中,如果我打印出 JSON,我得到:

{firstName: piet, lastName: venter}

Jackson 不喜欢这种格式的数据,它 returns 状态 400 和 The request sent by the client was syntactically incorrect.

如果我在所有字段上都加上引号,Jackson 会接受数据并且我会收到回复。

{"firstName": "piet", "lastName": "venter"}

在 dart 中,我构建了一个 Map<String, String> data = {}; 然后遍历所有表单字段并执行 data.putIfAbsent(input.name, () => input.value);

现在,当我调用 data.toString() 时,我得到了未加引号的 JSON,我猜它是无效的 JSON.

如果我 import 'dart:convert' show JSON; 并尝试 JSON.encode(data).toString(); 我得到相同的未引用 JSON.

手动添加双引号似乎可行:

data.putIfAbsent("\"" + input.name + "\"", () => "\"" + input.value + "\"");

Java 方面没有火箭科学:

@Controller
@RequestMapping("/seller")
@JsonIgnoreProperties(ignoreUnknown = true)
public class SellerController {

    @ResponseBody
    @RequestMapping(value = "/create", method = RequestMethod.POST, headers = {"Content-Type=application/json"})
    public Seller createSeller(@RequestBody Seller sellerRequest){

所以我的问题是,在 Dart 中是否有更简单的方法来构建 Jackson 期望的引用 JSON(除了手动转义引号和手动添加引号)? Jackson 可以配置为允许不带引号的 JSON 吗?

import 'dart:convert';
...
json.encode(data); // JSON.encode(data) in Dart 1.x

对我来说总是引述 JSON。
您无需致电 toString()

简单的方法

import 'dart:convert';
Map<String, dynamic> jsonData = {"name":"vishwajit"};
print(JsonEncoder().convert(jsonData));

如果数据内容是动态的,下面的函数可以帮助在服务器上发送 JSON 带引用的数据。可以像在 Dart 中转换字符串一样使用此函数。

导入内置 convert 库,其中包括 jsonDecode()jsonEncode() 方法:

import 'dart:convert';   //Don't forget to import this

dynamic convertJson(dynamic param) {
  const JsonEncoder encoder = JsonEncoder();
  final dynamic object = encoder.convert(param);
  return object;
}

你会use/call喜欢

Future<dynamic> postAPICallWithQuoted(String url, Map param, BuildContext context) async {
  final String encodedData = convertJson(param);
  print("Calling parameters: $encodedData");
  var jsonResponse;
  try {
    final response =  await http.post(url,
        body: encodedData).timeout(const Duration(seconds: 60),onTimeout : () => throw TimeoutException('The connection has timed out, Please try again!'));
  } on SocketException {
    throw FetchDataException(getTranslated(context, "You are not connected to internet"));
  } on TimeoutException {
    print('Time out');
    throw TimeoutException(getTranslated(context, "The connection has timed out, Please try again"));
  }
  return jsonResponse;
}