@@ -12,6 +12,8 @@ import 'package:source_gen/source_gen.dart';
12
12
13
13
import 'package:json_annotation/json_annotation.dart' ;
14
14
15
+ import 'utils.dart' ;
16
+
15
17
class JsonLiteralGenerator extends GeneratorForAnnotation <JsonLiteral > {
16
18
const JsonLiteralGenerator ();
17
19
@@ -44,7 +46,7 @@ class JsonLiteralGenerator extends GeneratorForAnnotation<JsonLiteral> {
44
46
String _jsonLiteralAsDart (dynamic value, bool asConst) {
45
47
if (value == null ) return 'null' ;
46
48
47
- if (value is String ) return _jsonStringAsDart (value);
49
+ if (value is String ) return escapeDartString (value);
48
50
49
51
if (value is bool || value is num ) return value.toString ();
50
52
@@ -74,7 +76,7 @@ String _jsonMapAsDart(Map<String, dynamic> value, bool asConst) {
74
76
} else {
75
77
buffer.writeln (',' );
76
78
}
77
- buffer.write (_jsonStringAsDart (k));
79
+ buffer.write (escapeDartString (k));
78
80
buffer.write (':' );
79
81
buffer.write (_jsonLiteralAsDart (v, asConst));
80
82
});
@@ -83,34 +85,3 @@ String _jsonMapAsDart(Map<String, dynamic> value, bool asConst) {
83
85
84
86
return buffer.toString ();
85
87
}
86
-
87
- String _jsonStringAsDart (String value) {
88
- var containsSingleQuote = value.contains ("'" );
89
- var contains$ = value.contains (r'$' );
90
-
91
- if (containsSingleQuote) {
92
- if (value.contains ('"' )) {
93
- // `value` contains both single and double quotes as well as `$`.
94
- // The only safe way to wrap the content is to escape all of the
95
- // problematic characters.
96
- var string = value
97
- .replaceAll ('\$ ' , '\\\$ ' )
98
- .replaceAll ('"' , '\\ "' )
99
- .replaceAll ("'" , "\\ '" );
100
- return "'$string '" ;
101
- } else if (contains$) {
102
- // `value` contains "'" and "$", but not '"'.
103
- // Safely wrap it in a raw string within double-quotes.
104
- return 'r"$value "' ;
105
- }
106
- return '"$value "' ;
107
- } else if (contains$) {
108
- // `value` contains "$", but no "'"
109
- // wrap it in a raw string using single quotes
110
- return "r'$value '" ;
111
- }
112
-
113
- // `value` contains no problematic characters - except for '"' maybe.
114
- // Wrap it in standard single-quotes.
115
- return "'$value '" ;
116
- }
0 commit comments