MCCCS
MCCCS

Reputation: 1022

GSON - Json Parsing Error

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

and

public class GsonUtils
{
    public static Gson gson = new Gson();
    public static Gson prettyGson = new GsonBuilder().setPrettyPrinting()
        .create();
    public static JsonParser jsonParser = new JsonParser();
}

were the classes I used to get the JSON and parse it. But when I run the first one, it reports the following stacktrace:

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

It tells me to add JsonReader.setLenient(true) to my code but my code doesn't use JsonReader. Then how can I add setLenient(true) to my code?

EDIT: Add API response (formatted):

{
  "statusCode": 401,
  "error": "Unauthorized",
  "message": "Invalid API Key. To get an api key use the /api command in game"
}

Upvotes: 3

Views: 6102

Answers (1)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 520878

I think you might be over complicating the use of the GSON library. The following code snippet works fine for me locally in 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());

Here I have used the overloaded version of Gson.fromJson() which takes a string, but there is also a version which takes a FileReader.

In your case, you might try this:

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

Upvotes: 3

Related Questions