本文介绍了如何在 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 JSON API 实现在 github 上,在 maven 中 部分在 Android 上.
This code uses org.json JSON API implementation that is available on github, in maven and partially on Android.
这篇关于如何在 Java 中检查给定字符串是否是有效的 JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!