如何解析json数据(如果它带有转义字符)以响应飞镖或颤动?

时间:2019-03-08 16:16:35

标签: dart flutter

我的json响应为{"quoteText":"You\'re not obligated to win. You\'re obligated to keep trying to do the best you can every day.", "quoteAuthor":"Marian Edelman"},我正在尝试通过Map<String, dynamic> quoteData = jsonDecode(response.body);进行解码,但收到此异常

[ERROR:flutter/shell/common/shell.cc(184)] Dart Error: Unhandled exception:
    E/flutter ( 5814): FormatException: Unrecognized string escape (at character 20)
    E/flutter ( 5814): {"quoteText":"You\'re not obligated to win. You\'re obligated to keep tryin...
    E/flutter ( 5814):                    ^
    E/flutter ( 5814): 
    E/flutter ( 5814): #0      _ChunkedJsonParser.fail (dart:convert/runtime/libconvert_patch.dart:1358:5)

尝试过json.decode()和做过flutter-remove-escape-sequence-in-dart,但是没有运气。有解决方法吗?

1 个答案:

答案 0 :(得分:1)

那不是valid json。单引号不能转义。要么您应该获取源代码来修复它,要么您可以尝试自己修复该字符串,方法是将所有\'替换为'

String fixed = badString.replaceAll(r"\'", "'");
json.decode(fixed);