Closed Warkeeper closed 4 years ago
I think it's pretty usual that a C client produces a json string which is ended with '\0', and the Java Client using gson to deserialize it. Is it possible to fix this issue?
I think it's pretty usual that a C client produces a json string which is ended with '\0'....
I would say that it should not produce a \0
-terminated payload, and the string you provided is actually a malformed JSON document, so Gson refuses to parse it.
Is it possible to fix this issue?
You can work around it by reading the JSON document via JsonReader
, a reader that reads JSON tokens lazily:
final Reader reader = new StringReader("{\"color\":\"red\",\"weight\":200}\0");
final JsonReader jsonReader = new JsonReader(reader);
final Apple apple = gson.fromJson(jsonReader, Apple.class);
System.out.println(apple);
This does not fail because JsonReader
reads the backing reader/input stream token by token, and once it consumes the final }
, it suspends parsing not failing at \0
. Once you ask it to parse/peek the next token with peek()
, you'll get the syntax error exception:
...
jsonReader.peek();
A brief conclusion:
StringReader
is actually reading a string), for performance reasons.FilterReader
/PushbackReader
to detect such malformed documents if you have to work with other libraries.Thanks for reply. @lyubomyr-shaydariv I can understand that Gson (with default configuration) refuses to deserialize a '\0'-ended string since it's not a valid JSON. However, when I set lenient to true, I may except that Gson will accept this kind of "JSON". Do I understand the lenient mode correctly?
@Warkeeper
To some extent. The lenient mode handles other special cases: https://github.com/google/gson/blob/ceae88bd6667f4263bbe02e6b3710b8a683906a2/gson/src/main/java/com/google/gson/stream/JsonReader.java#L295 (some of the items are weird IMHO). Your case is out of the list, but your issue is that Gson.deserialize
(at least in the java.lang.String
and java.io.Reader
overloads) first deserializes the JSON document,and then checks whether the input document was fully consumed: the dangling \0
character is neither a valid JSON token (as jsonReader.peek()
fails above right after the deserialization), nor the end of the JSON document.
Got it.Thanks a lot. @lyubomyr-shaydariv For now I will work around it by using JsonReader , and maybe in the future I would make a pr to add this case for the lenient mode. This issue could be closed for now.
Issue Description
When deserialize a string which ends with '\0' ,it shows this error:
If set lenient to true, the error changes to:
How to reproduce it
Here's the code.