GSON - JSON解析错误

问题描述:

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(); 
     } 

GSON - JSON解析错误

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" 
} 
+0

您可以发布您的代码是从API调用接收的文本? –

+0

@TimBiegeleisen完成。 – MCCCS

+0

[gson引发MalformedJsonException]可能的重复(http://*.com/questions/11484353/gson-throws-malformedjsonexception) – Yazan

我想你可能是在使用GSON库的复杂化。下面的代码片段,我能正常工作在本地的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 
+0

这两者都会有一点开销,因为您必须首先将其转换为字符串,或者先将其保存到磁盘。 –

+0

@Haroldo_OK我现在正在更新一个更适用于OP的解决方案。 –

+0

好吧,使用Reader(非FileReader)似乎是一个不错的选择。 –