gson throws MalformedJsonException
Solution 1:
I suspect that result1 has some characters at the end of it that you can't see in the debugger that follow the closing }
character. What's the length of result1
versus result2
? I'll note that result2
as you've quoted it has 169 characters.
GSON throws that particular error when there's extra characters after the end of the object that aren't whitespace, and it defines whitespace very narrowly (as the JSON spec does) - only \t
, \n
, \r
, and space count as whitespace. In particular, note that trailing NUL (\0
) characters do not count as whitespace and will cause this error.
If you can't easily figure out what's causing the extra characters at the end and eliminate them, another option is to tell GSON to parse in lenient mode:
Gson gson = new Gson();
JsonReader reader = new JsonReader(new StringReader(result1));
reader.setLenient(true);
Userinfo userinfo1 = gson.fromJson(reader, Userinfo.class);
Solution 2:
From my recent experience, JsonReader#setLenient
basically makes the parser very tolerant, even to allow malformed JSON data.
But for certain data retrieved from your trusted RESTful API(s), this error might be caused by trailing white spaces. In such cases, simply trim
the data would avoid the error:
String trimmed = result1.trim();
Then gson.fromJson(trimmed, T)
might work. Surely this only covers a special case, so YMMV.
Solution 3:
In the debugger you don't need to add back slashes, the input field understands the special chars.
In java code you need to escape the special chars