Dart: convert Map to JSON with all elements quoted

2020-06-08 16:48发布

问题:

I'm serializing a form in Dart into JSON then posting it to a Spring MVC backend using Jackson to deserialize the JSON.

In dart, if I print out the JSON, I'm getting:

{firstName: piet, lastName: venter}

Jackson doesn't like the data in this format, it returns a status 400 and The request sent by the client was syntactically incorrect.

If I put quotes around all the fields, Jackson accepts the data and I get a response back.

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

In dart I build a Map<String, String> data = {}; then loop through all form fields and do data.putIfAbsent(input.name, () => input.value);

Now when I call data.toString(), I get the unquoted JSON which I'm guessing is invalid JSON.

If I import 'dart:convert' show JSON; and try JSON.encode(data).toString(); I get the same unquoted JSON.

Manually appending double-quotes seems to work:

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

On the Java side there's no rocket science:

@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){

So my question, is there a less hacky way in Dart to build quoted JSON (other than manually escaping quotes and adding quotes manually) that Jackson expects? Can Jackson be configured to allow unquoted JSON ?

回答1:

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

always resulted in quoted JSON for me.
You don't need to call toString()



回答2:

Simple way

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