22
22
import com .google .gson .common .TestTypes .BagOfPrimitives ;
23
23
24
24
import com .google .gson .reflect .TypeToken ;
25
+
26
+ import java .util .Arrays ;
25
27
import java .util .Map ;
26
28
import junit .framework .TestCase ;
27
29
@@ -89,8 +91,8 @@ public void testTopLevelNullObjectDeserializationWithReaderAndSerializeNulls() {
89
91
}
90
92
91
93
public void testReadWriteTwoStrings () throws IOException {
92
- Gson gson = new Gson ();
93
- CharArrayWriter writer = new CharArrayWriter ();
94
+ Gson gson = new Gson ();
95
+ CharArrayWriter writer = new CharArrayWriter ();
94
96
writer .write (gson .toJson ("one" ).toCharArray ());
95
97
writer .write (gson .toJson ("two" ).toCharArray ());
96
98
CharArrayReader reader = new CharArrayReader (writer .toCharArray ());
@@ -102,8 +104,8 @@ public void testReadWriteTwoStrings() throws IOException {
102
104
}
103
105
104
106
public void testReadWriteTwoObjects () throws IOException {
105
- Gson gson = new Gson ();
106
- CharArrayWriter writer = new CharArrayWriter ();
107
+ Gson gson = new Gson ();
108
+ CharArrayWriter writer = new CharArrayWriter ();
107
109
BagOfPrimitives expectedOne = new BagOfPrimitives (1 , 1 , true , "one" );
108
110
writer .write (gson .toJson (expectedOne ).toCharArray ());
109
111
BagOfPrimitives expectedTwo = new BagOfPrimitives (2 , 2 , false , "two" );
@@ -132,4 +134,45 @@ public void testTypeMismatchThrowsJsonSyntaxExceptionForReaders() {
132
134
} catch (JsonSyntaxException expected ) {
133
135
}
134
136
}
137
+
138
+ /**
139
+ * Verifies that passing an {@link Appendable} which is not an instance of {@link Writer}
140
+ * to {@code Gson.toJson} works correctly.
141
+ */
142
+ public void testToJsonAppendable () {
143
+ class CustomAppendable implements Appendable {
144
+ final StringBuilder stringBuilder = new StringBuilder ();
145
+
146
+ @ Override
147
+ public Appendable append (char c ) throws IOException {
148
+ stringBuilder .append (c );
149
+ return this ;
150
+ }
151
+
152
+ @ Override
153
+ public Appendable append (CharSequence csq ) throws IOException {
154
+ if (csq == null ) {
155
+ append ("null" );
156
+ } else {
157
+ append (csq , 0 , csq .length ());
158
+ }
159
+ return this ;
160
+ }
161
+
162
+ public Appendable append (CharSequence csq , int start , int end ) throws IOException {
163
+ if (csq == null ) {
164
+ return append ("null" );
165
+ }
166
+
167
+ // According to doc, toString() must return string representation
168
+ String s = csq .toString ();
169
+ stringBuilder .append (s , start , end );
170
+ return this ;
171
+ }
172
+ }
173
+
174
+ CustomAppendable appendable = new CustomAppendable ();
175
+ gson .toJson (Arrays .asList ("test" , 123 , true ), appendable );
176
+ assertEquals ("[\" test\" ,123,true]" , appendable .stringBuilder .toString ());
177
+ }
135
178
}
0 commit comments