gson 抛出 MalformedJsonException [英] gson throws MalformedJsonException
问题描述
我正在使用 gson 将 json 字符串转换为 Java 对象.result2 的值与 result1 的值完全相同.(从调试器复制;添加了反斜杠)
I'm using gson to convert a json string to a Java-Object. The value of result2 is exactly the same as the value of result1. (Copied from debugger; Backslashs added)
转换 result1 时抛出以下异常:com.google.gson.JsonSyntaxException:com.google.gson.stream.MalformedJsonException:第 1 行第 170 列的预期 EOF
The following exception is thrown while converting result1: com.google.gson.JsonSyntaxException: com.google.gson.stream.MalformedJsonException: Expected EOF at line 1 column 170
转换 result2 工作正常.
json 字符串根据 jsonlint.com 是有效的.
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;
}
推荐答案
我怀疑 result1 末尾有一些字符,您在调试器中看不到 }
特点.result1
与 result2
的长度是多少?我会注意到您引用的 result2
有 169 个字符.
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 在对象末尾有额外的不是空格的字符时抛出该特定错误,并且它非常定义了空格(就像 JSON 规范那样) - 只有
、
、
和空格算作空白.特别要注意尾随的 NUL (