JAVA常用工具类-【3】判断是否是JSON

1、判断是不是JSON字符串

package com.day.util;
import org.apache.commons.lang.StringUtils;
import com.alibaba.fastjson.*;

public class IsJSON {
	public static void main(String[] args) {
		String jsonString="{\"fileType\":\"pdf\",\"seq\":1}";
		String jsonStringAnother="{\"fileType\":\"pdf\",\"seq\":1'}";//多个单引号
		System.out.println(isJSON(jsonString));
		System.out.println(isJSON(jsonStringAnother));
	}
	//判断是不是JSON
	public static boolean isJSON(String str){
		if(isJSONObject(str)||isJSONArray(str)){
			return true;
		}else{
			return false;
		}
	}
	//判断是不是JSON对象
	public static boolean isJSONObject(String str) {
		// 此处应该注意,不要使用StringUtils.isEmpty(),
		// 因为当content为"  "空格字符串时,JSONObject.parseObject可以解析成功,
		if(StringUtils.isBlank(str)){
			return false;
		}
		try {
			JSONObject jsonObject = JSONObject.parseObject(str);
			return true;
		} catch (Exception e) {
			return false;
		}
	}
	//判断是不是JSON数组
	public static boolean isJSONArray(String str) {
		if(StringUtils.isBlank(str)){
			return false;
		}
		StringUtils.isEmpty(str);
		try {
			JSONArray jsonStr = JSONArray.parseArray(str);
			return true;
		} catch (Exception e) {
			return false;
		}
	}
}

你可能感兴趣的:(json)