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

问题描述 投票:0回答:3

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

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

{firstName: piet, lastName: venter}

Jackson 不喜欢这种格式的数据,它返回状态 400 和

The request sent by the client was syntactically incorrect.

如果我在所有字段中加上引号,杰克逊会接受数据并收到回复。

{"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 吗?

json spring-mvc dart jackson
3个回答
92
投票
import 'dart:convert';
...
json.encode(data); // JSON.encode(data) in Dart 1.x

我总是得到引用的 JSON。
你不需要打电话

toString()


14
投票

简单的方法

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

0
投票

就这么做

Map<String, dynamic> response = {"name":"aditya", "age":"26"};

String jsonString = response.toString();
© www.soinside.com 2019 - 2024. All rights reserved.