【问题标题】:GSON - Json Parsing ErrorGSON - Json 解析错误
【发布时间】: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"
}

【问题讨论】:

标签: java json


【解决方案1】:

我认为您可能过于复杂了 GSON 库的使用。以下代码 sn-p 在 IntelliJ 本地对我来说可以正常工作:

Gson gson = new Gson();
String input = "{\"statusCode\": 401, error\": \"Unauthorized\", \"message\": \"Invalid API Key. To get an api key use the /api command in game\"}";
JsonElement json = gson.fromJson(input, JsonElement.class);
System.out.println(json.toString());

这里我使用了Gson.fromJson() 的重载版本,它接受一个字符串,但也有一个版本接受FileReader

在你的情况下,你可以试试这个:

JsonReader reader = new JsonReader(new InputStreamReader(
            new URL("http://api.mineplex.com/pc/player/abc?apiKey=1")
              .openConnection().getInputStream()));
JsonElement json = gson.fromJson(reader, JsonElement.class);
// use your JsonElement here

【讨论】:

  • 两者都会有一点开销,因为您必须先将其转换为字符串,或者先将其保存到磁盘。
  • @Haroldo_OK 我现在正在更新一个更适用于 OP 的解决方案。
  • 好吧,使用 Reader(非 FileReader)似乎是个不错的选择。
  • @TimBiegeleisen 不错的答案!另外,如何在不声明另一个变量的情况下将其转换为 JsonObject?
  • 也许你可以打电话给json.getAsJsonObject()
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多