工具篇——JsonUtil(用于校验字符串是否是合法的JSON格式)

写代码的四点:
     1.明确需求。要做什么?
     2.分析思路。要怎么做?(1,2,3……)
     3.确定步骤。每一个思路要用到哪些语句、方法和对象。
     4.代码实现。用具体的语言代码将思路实现出来。

学习新技术的四点:
     1.该技术是什么?
     2.该技术有什么特点?(使用需注意的方面)
     3.该技术怎么使用?(写Demo)
     4.该技术什么时候用?(在Project中的使用场景 )

----------------------早计划,早准备,早完成。-------------------------

代码如下:

package com.wy.test.other;

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

/**
 * 用于校验字符串是否是合法的JSON格式
 */
public class JsonUtil {
    private CharacterIterator it;
    private char c;
    private int col;
    private static JsonUtil instance;

    /**
     * 获取类的实例
     *
     * @return 类的实例
     */
    public static JsonUtil getInstance() {
        if (instance == null) {
            instance = new JsonUtil();
        }
        return instance;
    }

    /**
     * 验证一个字符串是否是合法的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 false;
        }

        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;
    }
}

在项目中的应用:

//非法JSON
String jsonStrIllegal = "illegal";
//合法JSON
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\""
        + "      }"
        + "  ]"
        + " }"
        + " ]"
        + "  }"
        + " }";
boolean validate = JsonUtil.getInstance().validate(jsonStr);
LogUtil.e("是合法的JSON吗?", validate + "");

你可能感兴趣的:(Android工具篇,Android常用工具类,一个灵活的胖子的进击之路)