如何检查给定字符串是否是Java中的有效JSON [英] How to check whether a given string is valid JSON in Java

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

问题描述

如何在Java中验证JSON字符串?或者我可以使用正则表达式解析它吗?

How do I validate a JSON string in Java? Or could I parse it using regular expressions?

推荐答案

一个疯狂的想法,尝试解析它并捕获异常:

A wild idea, try parsing it and catch the exception:

import org.json.*;

public boolean isJSONValid(String test) {
    try {
        new JSONObject(test);
    } catch (JSONException ex) {
        // edited, to include @Arthur's comment
        // e.g. in case JSONArray is valid as well...
        try {
            new JSONArray(test);
        } catch (JSONException ex1) {
            return false;
        }
    }
    return true;
}

此代码使用 org.json 可在在github上使用的JSON API实现 maven 和部分在Android上

This code uses org.json JSON API implementation that is available on github, in maven and partially on Android.

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

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