Gson throws a MalformedJsonException

I use gson to convert json string to Java-Object. The value of result2 is exactly the same as the value of result1 . (Copied from the debugger, added reverse salsa)

When converting result1, the following exception was thrown: com.google.gson.JsonSyntaxException: com.google.gson.stream.MalformedJsonException: expected EOF in row 1 of column 170

Converting result2 works fine.

The json string is valid according to jsonlint.com.

public static Userinfo getUserinfo() { String result1 = http.POST("https://www.bitstamp.net/api/balance/", postdata, true); String result2 = "{\"btc_reserved\": \"0\", \"fee\": \"0.5000\", \"btc_available\": \"0.10000000\", \"usd_reserved\": \"0\", \"btc_balance\": \"0.10000000\", \"usd_balance\": \"30.00\", \"usd_available\": \"30.00\"}"; Gson gson = new Gson(); Userinfo userinfo1 = gson.fromJson(result1, Userinfo.class); //throws Exception Userinfo userinfo2 = gson.fromJson(result2, Userinfo.class); //works fine return userinfo1; } private class Userinfo { public Userinfo(){ } public float usd_balance; public float btc_balance ; public float usd_reserved; public float btc_reserved; public float usd_available; public float btc_available; public float fee; public float last_update; } 
+49
java json gson
Jul 14 2018-12-14T00:
source share
3 answers

I suspect that result1 has several characters at the end that you don't see in the debugger that follow the closing character } . What is the length of result1 compared to result2 ? I note that result2 , as you indicated, has 169 characters.

GSON throws this specific error when extra characters after the end of an object are not spaces, and it defines nodes very narrowly (as the JSON specification does) - only \t , \n , \r , and a space is considered a space. In particular, note that trailing NUL characters ( \0 ) are not considered spaces and will cause this error .

If you cannot easily understand what causes the extra characters at the end and eliminate them, another option is to tell GSON about the parsing in soft mode:

 Gson gson = new Gson(); JsonReader reader = new JsonReader(new StringReader(result1)); reader.setLenient(true); Userinfo userinfo1 = gson.fromJson(reader, Userinfo.class); 
+79
Jul 15 2018-12-12T00:
source share

From my recent experience, JsonReader#setLenient basically makes the parser very tolerant, even to allow malformed JSON data.

But for certain data derived from your trusted RESTful APIs, this error may be caused by trailing spaces. In such cases, just trim data could avoid the error:

 String trimmed = result1.trim(); 

Then gson.fromJson(trimmed, T) should work as expected.

+14
Sep 17 '14 at 11:04
source share

In the debugger you do not need to add slashes, the input field understands special characters.

In java code you need to avoid special characters

+3
Jul 14 2018-12-14T00:
source share



All Articles