flutter JSON字符串化类似于Dart上的Web

wfauudbj  于 2022-11-17  发布在  Flutter
关注(0)|答案(2)|浏览(90)

I have the next Map

Map<String, dynamic> example = {
  'isActive': true,
  'age': 24,
  'name': 'Sam',
  'childrens': ['Jhon', 'Elisa']
};

And i need to Stringify like the JSON.stringify() on web, to have a result like that

"{\"isActive\":true,\"age\":24,\"name\":\"Sam\",\"childrens\":[\"Jhon\",\"Elisa\"]}"

Actually using the json.encode() the result its the next and obviously its not equal to the above

{"isActive":true,"age":24,"name":"Sam","childrens":["Jhon","Elisa"]}

I need stringify my Map to POST in a REST API, if the Stringify its not equal to the web, the web can not read that.

niknxzdl

niknxzdl1#

不同之处在于开头和结尾都有一个",以及每个"之前都有一个\
您可以想象一个简单的函数来执行此转换:

String stringify(String json) => '"${json.replaceAll('"', '\\"')}"';
kdfy810k

kdfy810k2#

as the previous answer. Using the same function of @MickaelHrndz

String stringify(String json) => '"${json.replaceAll('"', '\\"')}"';

when using it. as your map variable "example" you need to encode it first before stringifying
Use the following => stringify(json.encode(example)) . It will give you the correct format but don't forget to import this one import 'dart:convert'; to use the encode function which I mentioned before
Good luck for you ^_^

Update ------> You can simply encode twice json.encode(json.encode(example));

相关问题