@@ -183,29 +183,42 @@ public static String rowToString(JSONArray ja, char delimiter) {
183183 sb .append (delimiter );
184184 }
185185 Object object = ja .opt (i );
186- if (object != null ) {
187- String string = object .toString ();
188- if (!string .isEmpty () && (string .indexOf (delimiter ) >= 0 ||
189- string .indexOf ('\n' ) >= 0 || string .indexOf ('\r' ) >= 0 ||
190- string .indexOf (0 ) >= 0 || string .charAt (0 ) == '"' )) {
191- sb .append ('"' );
192- int length = string .length ();
193- for (int j = 0 ; j < length ; j += 1 ) {
194- char c = string .charAt (j );
195- if (c >= ' ' && c != '"' ) {
196- sb .append (c );
197- }
198- }
199- sb .append ('"' );
200- } else {
201- sb .append (string );
202- }
203- }
186+ appendRowValue (sb , object , delimiter );
204187 }
205188 sb .append ('\n' );
206189 return sb .toString ();
207190 }
208191
192+ private static void appendRowValue (StringBuilder sb , Object object , char delimiter ) {
193+ if (object == null ) {
194+ return ;
195+ }
196+ String string = object .toString ();
197+ if (shouldQuoteValue (string , delimiter )) {
198+ appendQuotedValue (sb , string );
199+ } else {
200+ sb .append (string );
201+ }
202+ }
203+
204+ private static boolean shouldQuoteValue (String string , char delimiter ) {
205+ return !string .isEmpty () && (string .indexOf (delimiter ) >= 0 ||
206+ string .indexOf ('\n' ) >= 0 || string .indexOf ('\r' ) >= 0 ||
207+ string .indexOf (0 ) >= 0 || string .charAt (0 ) == '"' );
208+ }
209+
210+ private static void appendQuotedValue (StringBuilder sb , String string ) {
211+ sb .append ('"' );
212+ int length = string .length ();
213+ for (int j = 0 ; j < length ; j += 1 ) {
214+ char c = string .charAt (j );
215+ if (c >= ' ' && c != '"' ) {
216+ sb .append (c );
217+ }
218+ }
219+ sb .append ('"' );
220+ }
221+
209222 /**
210223 * Produce a JSONArray of JSONObjects from a comma delimited text string,
211224 * using the first row as a source of names.
0 commit comments