MBy*_*ByD 249
一个疯狂的想法,尝试解析它并捕获异常:
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;
}
Run Code Online (Sandbox Code Playgroud)
此代码使用org.json JSON API实现,该实现可在github,maven和部分Android上使用.
Jea*_*ean 89
杰克逊图书馆
一种选择是使用杰克逊图书馆.首先导入最新版本(现在是):
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.7.0</version>
</dependency>
Run Code Online (Sandbox Code Playgroud)
然后,您可以按如下方式实现正确的答案:
import com.fasterxml.jackson.databind.ObjectMapper;
public final class JSONUtils {
private JSONUtils(){}
public static boolean isJSONValid(String jsonInString ) {
try {
final ObjectMapper mapper = new ObjectMapper();
mapper.readTree(jsonInString);
return true;
} catch (IOException e) {
return false;
}
}
}
Run Code Online (Sandbox Code Playgroud)
谷歌GSON选项
另一种选择是使用Google Gson.导入依赖项:
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.5</version>
</dependency>
Run Code Online (Sandbox Code Playgroud)
同样,您可以将提议的解决方案实现为:
import com.google.gson.Gson;
public final class JSONUtils {
private static final Gson gson = new Gson();
private JSONUtils(){}
public static boolean isJSONValid(String jsonInString) {
try {
gson.fromJson(jsonInString, Object.class);
return true;
} catch(com.google.gson.JsonSyntaxException ex) {
return false;
}
}
}
Run Code Online (Sandbox Code Playgroud)
这里有一个简单的测试:
//A valid JSON String to parse.
String validJsonString = "{ \"developers\": [{ \"firstName\":\"Linus\" , \"lastName\":\"Torvalds\" }, " +
"{ \"firstName\":\"John\" , \"lastName\":\"von Neumann\" } ]}";
// Invalid String with a missing parenthesis at the beginning.
String invalidJsonString = "\"developers\": [ \"firstName\":\"Linus\" , \"lastName\":\"Torvalds\" }, " +
"{ \"firstName\":\"John\" , \"lastName\":\"von Neumann\" } ]}";
boolean firstStringValid = JSONUtils.isJSONValid(VALID_JSON_STRING); //true
boolean secondStringValid = JSONUtils.isJSONValid(NOT_VALID_JSON_STRING); //false
Run Code Online (Sandbox Code Playgroud)
请注意,由于尾随逗号将在发布中修复,因此可能存在"次要"问题3.0.0.
小智 15
使用Google Gson,您可以使用JsonParser:
import com.google.gson.JsonParser;
JsonParser parser = new JsonParser();
parser.parse(json_string); // throws JsonSyntaxException
Run Code Online (Sandbox Code Playgroud)
npi*_*nti 12
您可以使用JSONUtils库中提供的.mayBeJSON(String str).
这取决于您要通过验证证明的内容。当然,按照其他人的建议解析json比使用正则表达式更好,因为json的语法比仅用正则表达式所代表的语法更复杂。
如果只能通过Java代码解析json,请使用相同的解析器进行验证。
但是,仅进行解析并不一定会告诉您它是否会在其他环境中被接受。例如
如果您的验证需要非常彻底,则可以:
| 归档时间: |
|
| 查看次数: |
210057 次 |
| 最近记录: |