Home  >  Article  >  Java  >  How to determine whether a string is in json format in java

How to determine whether a string is in json format in java

王林
王林Original
2019-11-21 14:44:3816219browse

How to determine whether a string is in json format in java

#1. Simply judge whether it is in json format. Judgment rules: judge whether the first and last letters are {} or []. If they are neither, it is not a text in JSON format.

The code is implemented as follows:

public static boolean getJSONType(String str) {
	boolean result = false;
	if (StringUtils.isNotBlank(str)) {
		str = str.trim();
		if (str.startsWith("{") && str.endsWith("}")) {
			result = true;
		} else if (str.startsWith("[") && str.endsWith("]")) {
			result = true;
		}
	}
	return result;
}

2, Judged by fastjson parsing, if the parsing is successful, it is json format; otherwise, it is not json format

The code is implemented as follows:

public static boolean isJSON2(String str) {
	boolean result = false;
	try {
		Object obj=JSON.parse(str);
		result = true;
	} catch (Exception e) {
		result=false;
	}
	return result;
}

Recommended tutorial: java introductory tutorial

The above is the detailed content of How to determine whether a string is in json format in java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn