|
6 | 6 |
|
7 | 7 | import java.io.Closeable; |
8 | 8 | import java.io.IOException; |
9 | | -import java.io.StringWriter; |
10 | 9 | import java.io.Writer; |
11 | 10 | import java.lang.annotation.Annotation; |
12 | 11 | import java.lang.reflect.Field; |
@@ -2248,7 +2247,10 @@ public Object optQuery(JSONPointer jsonPointer) { |
2248 | 2247 | */ |
2249 | 2248 | @SuppressWarnings("resource") |
2250 | 2249 | public static String quote(String string) { |
2251 | | - StringWriter sw = new StringWriter(); |
| 2250 | + if (string == null || string.isEmpty()) { |
| 2251 | + return "\"\""; |
| 2252 | + } |
| 2253 | + Writer sw = new StringBuilderWriter(string.length() + 2); |
2252 | 2254 | try { |
2253 | 2255 | return quote(string, sw).toString(); |
2254 | 2256 | } catch (IOException ignored) { |
@@ -2647,7 +2649,10 @@ public String toString() { |
2647 | 2649 | */ |
2648 | 2650 | @SuppressWarnings("resource") |
2649 | 2651 | public String toString(int indentFactor) throws JSONException { |
2650 | | - StringWriter w = new StringWriter(); |
| 2652 | + // 6 characters are the minimum to serialise a key value pair e.g.: "k":1, |
| 2653 | + // and we don't want to oversize the initial capacity |
| 2654 | + int initialSize = map.size() * 6; |
| 2655 | + Writer w = new StringBuilderWriter(Math.max(initialSize, 16)); |
2651 | 2656 | return this.write(w, indentFactor, 0).toString(); |
2652 | 2657 | } |
2653 | 2658 |
|
@@ -2790,13 +2795,18 @@ static final Writer writeValue(Writer writer, Object value, |
2790 | 2795 | if (value == null || value.equals(null)) { |
2791 | 2796 | writer.write("null"); |
2792 | 2797 | } else if (value instanceof JSONString) { |
| 2798 | + // JSONString must be checked first, so it can overwrite behaviour of other types below |
2793 | 2799 | Object o; |
2794 | 2800 | try { |
2795 | 2801 | o = ((JSONString) value).toJSONString(); |
2796 | 2802 | } catch (Exception e) { |
2797 | 2803 | throw new JSONException(e); |
2798 | 2804 | } |
2799 | 2805 | writer.write(o != null ? o.toString() : quote(value.toString())); |
| 2806 | + } else if (value instanceof String) { |
| 2807 | + // assuming most values are Strings, so testing it early |
| 2808 | + quote(value.toString(), writer); |
| 2809 | + return writer; |
2800 | 2810 | } else if (value instanceof Number) { |
2801 | 2811 | // not all Numbers may match actual JSON Numbers. i.e. fractions or Imaginary |
2802 | 2812 | final String numberAsString = numberToString((Number) value); |
|
0 commit comments