Dart: convert Map to JSON with all elements quoted Dart: convert Map to JSON with all elements quoted dart dart

Dart: convert Map to JSON with all elements quoted


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 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 thisdynamic 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;}