Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dart: convert Map to JSON with all elements quoted

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 ?

like image 964
Jan Vladimir Mostert Avatar asked Mar 27 '15 05:03

Jan Vladimir Mostert


People also ask

What does jsonEncode do flutter?

Converts object to a JSON string. If value contains objects that are not directly encodable to a JSON string (a value that is not a number, boolean, string, null, list or a map with string keys), the toEncodable function is used to convert it to an object that must be directly encodable.

How do I change my map to list in Dart?

Another way to convert Map to a Dart List is to use Iterable map() method. list = map. entries. map((e) => Customer(e.

Can we send map in JSON?

We need to use the JSON-lib library for serializing and de-serializing a Map in JSON format. Initially, we can create a POJO class and pass this instance as an argument to the put() method of Map class and finally add this map instance to the accumulateAll() method of JSONObject.


2 Answers

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()

like image 62
Günter Zöchbauer Avatar answered Oct 01 '22 03:10

Günter Zöchbauer


Simple way

import 'dart:convert'; Map<String, dynamic> jsonData = {"name":"vishwajit"}; print(JsonEncoder().convert(jsonData)); 
like image 30
vishwajit76 Avatar answered Oct 01 '22 01:10

vishwajit76