Home > Java > JavaBase > body text

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

王林
Release: 2019-11-21 14:44:38
Original
16311 people have browsed it

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;
}
Copy after login

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;
}
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template