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

前端 未结 5 546
天涯浪人
天涯浪人 2020-12-05 08:35

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 boo         


        
5条回答
  •  醉话见心
    2020-12-05 08:59

    this works for me

    public static boolean isJson(String Json) {
        Gson gson = new Gson();
        try {
            gson.fromJson(Json, Object.class);
            Object jsonObjType = gson.fromJson(Json, Object.class).getClass();
            if(jsonObjType.equals(String.class)){
                return false;
            }
            return true;
        } catch (com.google.gson.JsonSyntaxException ex) {
            return false;
        }
    }
    

提交回复
热议问题