How to check if JSON is valid in Java using GSON?

gson, java, json

Solution

I found solution but using `org.json` library, according to How to check whether a given string is valid JSON in Java

public static boolean isJson(String Json) {
        try {
            new JSONObject(Json);
        } catch (JSONException ex) {
            try {
                new JSONArray(Json);
            } catch (JSONException ex1) {
                return false;
            }
        }
        return true;
    }

Now random looking string `bncjbhjfjhj` is `false` and `{"status": "UP"}` is true.

Problem

I have method that have to check if JSON is valid, found on How to check whether a given string is valid JSON in Java but it doesn't work. ``` public static boolean isJson(String Json) { Gson gson = new Gson(); try { gson.fromJson(Json, Object.class); return true; } catch (com.google.gson.JsonSyntaxException ex) { return false; } } ``` If I use this method with some string it always returns true. For example: ``` System.out.println(renderHtml.isJson("{\"status\": \"UP\"}")); ``` it gave me `true`, and ``` System.out.println(renderHtml.isJson("bncjbhjfjhj")); ``` gave me `true` also.

Original source

Related problems