如何使用GSON检查JSON在Java中是否有效? [英] How to check if JSON is valid in Java using GSON?

查看:357
本文介绍了如何使用GSON检查JSON在Java中是否有效?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有方法必须检查JSON是否有效,发现于如何检查给定的字符串是否是Java中的有效JSON ,但它不起作用。

  public static boolean isJson(String Json){
Gson gson = new Gson();
尝试{
gson.fromJson(Json,Object.class);
返回true;
} catch(com.google.gson.JsonSyntaxException ex){
return false;




$ b如果我用一些字符串使用这个方法,它总是返回真正。例如:

  System.out.println(renderHtml.isJson({\status \:\向上\})); 

它给了我 true



  System.out.println(renderHtml.isJson(bncjbhjfjhj)); 

同样给了我 true

解决方案

我找到了解决方案,但使用 org.json 库,根据如何检查给定的字符串在Java中是有效的JSON

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

$ / code>

现在随机查找字符串 bncjbhjfjhj false {status:UP} 为真。


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.

解决方案

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.

这篇关于如何使用GSON检查JSON在Java中是否有效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆