首页 java实战 Java JSON 验证实例子

Java JSON 验证实例子

JAVA  验证 json是否是符合格式 实际演示地址为 :  http://tool.liyongqiang.com/…

JAVA  验证 json是否是符合格式

实际演示地址为 :  http://tool.liyongqiang.com/tool/findJson

暂时还没有别的错误

import java.text.CharacterIterator;
import java.text.StringCharacterIterator;
import java.util.HashMap;
/**
 * 用于校验一个字符串是否是合法的JSON格式
 * @author liShuMin
 *
 */
public class JsonValidator {

    private CharacterIterator it;
    private char              c;
    private int               col;
    public static String  errorStr="";

    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"));
         errorStr+="type:"+type+", col:"+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(new JsonValidator().validate(jsonStr));
    	System.out.println(errorStr);
    }
}

 

免责声明:文章内容不代表本站立场,本站不对其内容的真实性、完整性、准确性给予任何担保、暗示和承诺,仅供读者参考,文章版权归原作者所有。如本文内容影响到您的合法权益(内容、图片等),请及时联系本站,我们会及时删除处理。

为您推荐

mysql 统计日期 今天,昨天,上个月,这个月 ,一年

mysql 统计日期 今天,昨天,上个月,这个月 ,一年

查询5分钟前的数据 select * from table where end_date between date_ad...
Illegal key size or default parameters

Illegal key size or default parameters

简介: java中使用AES对称加密后,请求报错: Caused by: java.lang.RuntimeExcept...
nginx跨域问题

nginx跨域问题

add_header Access-Control-Allow-Origin *; add_header Access-...
Ajax请求发送成功但不进success的解决方法

Ajax请求发送成功但不进success的解决方法

dataType:’Text’ 格式严格按照服务端返回的数据来
【java】post请求参数全大写后台接不到参数

【java】post请求参数全大写后台接不到参数

测试验证的时候发现,接收不到请求参数   驼峰正常 springMVC使用的是Jackson来解析json格式的请求报文...
返回顶部