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 ?
Solution 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()
Solution 2:
Simple way
import 'dart:convert';
Map<String, dynamic> jsonData = {"name":"vishwajit"};
print(JsonEncoder().convert(jsonData));
Solution 3:
If the data content dynamic, below is a function to help to send JSON data with Quoted send on the server. This function can be used just like you would with a convert a String in Dart.
Import the builtin convert
library, which includes the jsonDecode()
and jsonEncode()
methods:
import 'dart:convert'; //Don't forget to import this
dynamic convertJson(dynamic param) {
const JsonEncoder encoder = JsonEncoder();
final dynamic object = encoder.convert(param);
return object;
}
You would use/call it like
Future<dynamic> postAPICallWithQuoted(String url, Map param, BuildContext context) async {
final String encodedData = convertJson(param);
print("Calling parameters: $encodedData");
var jsonResponse;
try {
final response = await http.post(url,
body: encodedData).timeout(const Duration(seconds: 60),onTimeout : () => throw TimeoutException('The connection has timed out, Please try again!'));
} on SocketException {
throw FetchDataException(getTranslated(context, "You are not connected to internet"));
} on TimeoutException {
print('Time out');
throw TimeoutException(getTranslated(context, "The connection has timed out, Please try again"));
}
return jsonResponse;
}