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

Jan*_*ert 12 json spring-mvc jackson dart

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

在飞镖中,如果我打印出JSON,我会得到:

{firstName: piet, lastName: venter}
Run Code Online (Sandbox Code Playgroud)

杰克逊不喜欢这种格式的数据,它返回状态400和 The request sent by the client was syntactically incorrect.

如果我在所有字段周围加上引号,杰克逊接受数据并得到回复.

{"firstName": "piet", "lastName": "venter"}
Run Code Online (Sandbox Code Playgroud)

在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 + "\"");
Run Code Online (Sandbox Code Playgroud)

在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){
Run Code Online (Sandbox Code Playgroud)

所以我的问题是,在Dart构建引用的JSON(除手动转义引号和手动添加引号之外)是否有一种不太常见的方式,杰克逊期望?杰克逊可以配置为允许不带引号的JSON吗?

Gün*_*uer 24

import 'dart:convert'; json.encode(data)(JSON.encode(data)飞镖1)总是为我引用引用的JSON(你不需要打电话toString()

  • 发现问题,JSON.encode 确实有效。谢谢甘特!一定是困倦让我错过明显的东西。 (3认同)

vis*_*hwa 9

简单的方法

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