【发布时间】:2017-04-12 07:47:31
【问题描述】:
try{
JsonElement rawJson =
GsonUtils.JsonParser.parse(new InputStreamReader(
new URL("http://api.mineplex.com/pc/player/abc?apiKey=1")
.openConnection().getInputStream()));
}catch(JsonIOException | JsonSyntaxException | IOException e){
e.printStackTrace();
}
和
public class GsonUtils
{
public static Gson gson = new Gson();
public static Gson prettyGson = new GsonBuilder().setPrettyPrinting()
.create();
public static JsonParser jsonParser = new JsonParser();
}
是我用来获取 JSON 并解析它的类。但是当我运行第一个时,它会报告以下堆栈跟踪:
com.google.gson.JsonSyntaxException: com.google.gson.stream.MalformedJsonException: Use JsonReader.setLenient(true) to accept malformed JSON at line 2 column 2
at com.google.gson.JsonParser.parse(JsonParser.java:65)
...
Caused by: com.google.gson.stream.MalformedJsonException: Use JsonReader.setLenient(true) to accept malformed JSON at line 2 column 2
at com.google.gson.stream.JsonReader.syntaxError(JsonReader.java:1505)
at com.google.gson.stream.JsonReader.checkLenient(JsonReader.java:1386)
at com.google.gson.stream.JsonReader.doPeek(JsonReader.java:531)
at com.google.gson.stream.JsonReader.peek(JsonReader.java:414)
at com.google.gson.JsonParser.parse(JsonParser.java:60)
... 13 more
它告诉我将JsonReader.setLenient(true) 添加到我的代码中,但我的代码不使用 JsonReader。那么如何将setLenient(true) 添加到我的代码中?
编辑:添加 API 响应(格式化):
{
"statusCode": 401,
"error": "Unauthorized",
"message": "Invalid API Key. To get an api key use the /api command in game"
}
【问题讨论】:
-
您能否发布您的代码从 API 调用接收到的文本?
-
@TimBiegeleisen 完成。
-
这很奇怪。它似乎是完全有效的 JSON;你确定这正是提供给 GSON 的内容吗?
-
你确定输入后没有多余的字符吗? stackoverflow.com/a/11488385/679240