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 ?
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.
Another way to convert Map to a Dart List is to use Iterable map() method. list = map. entries. map((e) => Customer(e.
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.
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()
Simple way
import 'dart:convert'; Map<String, dynamic> jsonData = {"name":"vishwajit"}; print(JsonEncoder().convert(jsonData));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With