The reason it doesn't work is because if you concatenate two JSON
strings, the output is not valid JSON.
Here is a test I wrote (borrowing from your code) to illustrate this:
public void testReadWriteTwoObjects() throws IOException {
Gson gson= new Gson();
CharArrayWriter writer= new CharArrayWriter();
BagOfPrimitives expectedOne = new BagOfPrimitives(1, 1, true,
"one");
writer.write(gson.toJson(expectedOne).toCharArray());
BagOfPrimitives expectedTwo = new BagOfPrimitives(2, 2, false,
"two");
writer.write(gson.toJson(expectedTwo).toCharArray());
System.out.println(writer.toCharArray());
CharArrayReader reader = new CharArrayReader(writer.toCharArray
());
BagOfPrimitives actualOne = gson.fromJson(reader,
BagOfPrimitives.class);
assertEquals("one", actualOne.stringValue);
BagOfPrimitives actualTwo = gson.fromJson(reader,
BagOfPrimitives.class);
assertEquals("two", actualTwo.stringValue);
}
The output JSON is:
{"longValue":1,"intValue":1,"booleanValue":true,"stringValue":"one"}
{"longValue":2,"intValue":2,"booleanValue":false,"stringValue":"two"}
Now when a JSON parser is parsing this input, it would see an invalid
start of an Object where the second { starts. I dont know how Jetty
handles it, but it probably is parsing the input selectively. Gson
uses a real parser and has a parsing phase which will reject any
invalid input.
I will look into modifying Gson so that its parser stops parsing when
the initial production finishes.
Inder
ps. The BagOfPrimitives is defined to be:
public static class BagOfPrimitives {
public static final long DEFAULT_VALUE = 0;
public long longValue;
public int intValue;
public boolean booleanValue;
public String stringValue;
public BagOfPrimitives(long longValue, int intValue, boolean
booleanValue, String stringValue) {
this.longValue = longValue;
this.intValue = intValue;
this.booleanValue = booleanValue;
this.stringValue = stringValue;