您的位置:首页 > Web前端 > JavaScript

判断是否JSON格式,日期,整数和小数的工具类

2017-12-12 19:47 423 查看
做ESB接口开发和Excel上传校验的时候遇到校验的问题,特意整理了一些工具类。

JsonValidator判断是否为json格式的字符串,不用try-catch。

import java.text.CharacterIterator;
import java.text.StringCharacterIterator;

public class JsonValidator {

private CharacterIterator it;
private char              c;
private int               col;

public JsonValidator(){
}

/**
* 验证一个字符串是否是合法的JSON串
*
* @param input 要验证的字符串
* @return true-合法 ,false-非法
*/
public boolean validate(String input) {
input = input.trim();
boolean ret = valid(input);
return ret;
}

private boolean valid(String input) {
if ("".equals(input)) return true;

boolean ret = true;
it = new StringCharacterIterator(input);
c = it.first();
col = 1;
if (!value()) {
ret = error("value", 1);
} else {
skipWhiteSpace();
if (c != CharacterIterator.DONE) {
ret = error("end", col);
}
}

return ret;
}

private boolean value() {
return literal("true") || literal("false") || literal("null") || string() || number() || object() || array();
}

private boolean literal(String text) {
CharacterIterator ci = new StringCharacterIterator(text);
char t = ci.first();
if (c != t) return false;

int start = col;
boolean ret = true;
for (t = ci.next(); t != CharacterIterator.DONE; t = ci.next()) {
if (t != nextCharacter()) {
ret = false;
break;
}
}
nextCharacter();
if (!ret) error("literal " + text, start);
return ret;
}

private boolean array() {
return aggregate('[', ']', false);
}

private boolean object() {
return aggregate('{', '}', true);
}

private boolean aggregate(char entryCharacter, char exitCharacter, boolean prefix) {
if (c != entryCharacter) return false;
nextCharacter();
skipWhiteSpace();
if (c == exitCharacter) {
nextCharacter();
return true;
}

for (;;) {
if (prefix) {
int start = col;
if (!string()) return error("string", start);
skipWhiteSpace();
if (c != ':') return error("colon", col);
nextCharacter();
skipWhiteSpace();
}
if (value()) {
skipWhiteSpace();
if (c == ',') {
nextCharacter();
} else if (c == exitCharacter) {
break;
} else {
return error("comma or " + exitCharacter, col);
}
} else {
return error("value", col);
}
skipWhiteSpace();
}

nextCharacter();
return true;
}

private boolean number() {
if (!Character.isDigit(c) && c != '-') return false;
int start = col;
if (c == '-') nextCharacter();
if (c == '0') {
nextCharacter();
} else if (Character.isDigit(c)) {
while (Character.isDigit(c))
nextCharacter();
} else {
return error("number", start);
}
if (c == '.') {
nextCharacter();
if (Character.isDigit(c)) {
while (Character.isDigit(c))
nextCharacter();
} else {
return error("number", start);
}
}
if (c == 'e' || c == 'E') {
nextCharacter();
if (c == '+' || c == '-') {
nextCharacter();
}
if (Character.isDigit(c)) {
while (Character.isDigit(c))
nextCharacter();
} else {
return error("number", start);
}
}
return true;
}

private boolean string() {
if (c != '"') return false;

int start = col;
boolean escaped = false;
for (nextCharacter(); c != CharacterIterator.DONE; nextCharacter()) {
if (!escaped && c == '\\') {
escaped = true;
} else if (escaped) {
if (!escape()) {
return false;
}
escaped = false;
} else if (c == '"') {
nextCharacter();
return true;
}
}
return error("quoted string", start);
}

private boolean escape() {
int start = col - 1;
if (" \\\"/bfnrtu".indexOf(c) < 0) {
return error("escape sequence  \\\",\\\\,\\/,\\b,\\f,\\n,\\r,\\t  or  \\uxxxx ", start);
}
if (c == 'u') {
if (!ishex(nextCharacter()) || !ishex(nextCharacter()) || !ishex(nextCharacter())
|| !ishex(nextCharacter())) {
return error("unicode escape sequence  \\uxxxx ", start);
}
}
return true;
}

private boolean ishex(char d) {
return "0123456789abcdefABCDEF".indexOf(c) >= 0;
}

private char nextCharacter() {
c = it.next();
++col;
return c;
}

private void skipWhiteSpace() {
while (Character.isWhitespace(c)) {
nextCharacter();
}
}

private boolean error(String type, int col) {
System.out.printf("type: %s, col: %s%s", type, col, System.getProperty("line.separator"));
return false;
}
public static void main(String[] args){
//String jsonStr = "{\"website\":\"oschina.net\"}";
String jsonStr = "{"
+ " \"ccobjtypeid\": \"1001\","
+ " \"fromuser\": \"李四\","
+ " \"touser\": \"张三\","
+ "  \"desc\": \"描述\","
+ "  \"subject\": \"主题\","
+ "  \"attach\": \"3245,3456,4345,4553\","
+ " \"data\": {"
+ "    \"desc\": \"测试对象\","
+ "     \"dataid\": \"22\","
+ "    \"billno\": \"TEST0001\","
+ "    \"datarelation\":["
+ " {"
+ "  \"dataname\": \"关联对象1\","
+ "  \"data\": ["
+ "      {"
+ "    \"dataid\": \"22\","
+ "          \"datalineid\": \"1\","
+ "          \"content1\": \"test1\","
+ "          \"content2\": \"test2\""
+ "      }"
+ "  ]"
+ " }"
+ " ]"
+ "  }"
+ " }";
System.out.println(jsonStr+":"+new JsonValidator().validate(jsonStr));
}
}


DateTimeValidator 校验时间格式

`public class DateTimeValidator {

public static boolean dateCheck(String checkValue)
{
checkValue = "2008-09-11 14:17:11";
DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd HH:mm:ss");
Date d = null;
if(checkValue != null && !checkValue.equals(""))
{
if(checkValue.split("/").length > 1)
{ dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); }
if (checkValue.split("-").length > 1)
{dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  }
}else { return false; }

try
{ d = dateFormat.parse(checkValue);}
catch(Exception e)
{ return false;}
String eL= "^((\\d{2}(([02468][048])|([13579][26]))[\\-\\/\\s]?((((0?[13578])|(1[02]))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])))))|(\\d{2}(([02468][1235679])|([13579][01345789]))[\\-\\/\\s]?((((0?[13578])|(1[02]))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/\\s]?((0?[1-9])|(1[0-9])|(2[0-8]))))))(\\s(((0?[0-9])|([1-2][0-9]))\:([0-5]?[0-9])((\\s)|(\:([0-5]?[0-9])))))?$";
Pattern p = Pattern.compile(eL);
Matcher m = p.matcher(checkValue);
boolean b = m.matches();
if(b) { return  true; }
else  { return false; }
}


}`

NumberValidationUtils 校验整数小数的类型

public class NumberValidationUtils {

private static boolean isMatch(String regex, String orginal){
if (orginal == null || orginal.trim().equals("")) {
return false;
}
Pattern pattern = Pattern.compile(regex);
Matcher isNum = pattern.matcher(orginal);
return isNum.matches();
}

public static boolean isPositiveInteger(String orginal) {
return isMatch("^\\+{0,1}[1-9]\\d*", orginal);
}

public static boolean isNegativeInteger(String orginal) {
return isMatch("^-[1-9]\\d*", orginal);
}

public static boolean isWholeNumber(String orginal) {
return isMatch("[+-]{0,1}0", orginal) || isPositiveInteger(orginal) || isNegativeInteger(orginal);
}

public static boolean isPositiveDecimal(String orginal){
return isMatch("\\+{0,1}[0]\\.[1-9]*|\\+{0,1}[1-9]\\d*\\.\\d*", orginal);
}

public static boolean isNegativeDecimal(String orginal){
return isMatch("^-[0]\\.[1-9]*|^-[1-9]\\d*\\.\\d*", orginal);
}

public static boolean isDecimal(String orginal){
return isMatch("[-+]{0,1}\\d+\\.\\d*|[-+]{0,1}\\d*\\.\\d+", orginal);
}

public static boolean isRealNumber(String orginal){
return isWholeNumber(orginal) || isDecimal(orginal);
}


}

因为try-catch捕捉异常耗性能,所以少用,尽量用别的校验方式。

搜罗而来,原处已忘。见谅
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: