• JSONObject和JSONArray区别及注意事项


    1、JSONObject和JSONArray的数据表示形式

    JSONObject的数据是用 { } 来表示的,

        例如:   {"name":"John","age":30,"city":"New York"}
    
    • 1

    而JSONArray,顾名思义是由JSONObject构成的数组,用 [ { } , { } , … , { } ] 来表示

       例如:   [{"name":"John","age":30,"city":"New York"}] ; 
    
    • 1

    2、解析json及可能遇到的问题

    		String str1 = "{\"name\":\"John\",\"age\":30,\"city\":\"New York\"}";
            String str2 = "[{\"name\":\"John\",\"age\":30,\"city\":\"New York\"}]";
            JSONObject jsonObject = JSONObject.parseObject(str1);
            JSONArray jsonArray = JSONArray.parseArray(str2);
    
    • 1
    • 2
    • 3
    • 4

    jsonObject对象如下
    在这里插入图片描述
    解析jsonArray的对象如下:
    在这里插入图片描述
    如果执行下面的代码

    		String str1 = "{\"name\":\"John\",\"age\":30,\"city\":\"New York\"}";
            String str2 = "[{\"name\":\"John\",\"age\":30,\"city\":\"New York\"}]";
            JSONObject jsonObject = JSONObject.parseObject(str2);
            JSONArray jsonArray = JSONArray.parseArray(str1);
    
    • 1
    • 2
    • 3
    • 4

    则会抛异常,即对象形式的json不能用parseArray进行解析,数组形式的json也不能用parseObject进行解析。

    3、解决方案

    可以使用JSON.parse()方法,该方法会自动判断json的类型,然后调不同的方法进行反解析。若需要需要知道具体对象,通过如下的方式进一步判断就可以了

    	   Object obj = JSON.parse(jsonString);
           if (obj instanceof JSONObject) {
               JSONObject jsonObject = (JSONObject) obj;  
           } else if (obj instanceof JSONArray) {
               JSONArray jsonArray = (JSONArray) obj;
               }
           }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    JSON.parse()方法中判断json串是什么类型的代码如下:

    public DefaultJSONParser(Object input, JSONLexer lexer, ParserConfig config) {
            this.resolveStatus = 0;
            this.derializer = new DefaultObjectDeserializer();
            this.contextArray = new ParseContext[8];
            this.contextArrayIndex = 0;
            this.resolveTaskList = new ArrayList();
            this.dateFormatPattern = JSON.DEFFAULT_DATE_FORMAT;
            this.input = input;
            this.lexer = lexer;
            this.config = config;
            this.symbolTable = config.getSymbolTable();
            lexer.nextToken(12);
        }
    
    public void nextToken(int expect) {
            while(true) {
                switch (expect) {
                    case 2:
                        if (this.ch >= '0' && this.ch <= '9') {
                            this.sp = 0;
                            this.pos = this.bp;
                            this.scanNumber();
                            return;
                        }
    
                        if (this.ch == '"') {
                            this.sp = 0;
                            this.pos = this.bp;
                            this.scanString();
                            return;
                        }
    
                        if (this.ch == '[') {
                            this.token = 14;
                            this.ch = this.buf[++this.bp];
                            return;
                        }
    
                        if (this.ch == '{') {
                            this.token = 12;
                            this.ch = this.buf[++this.bp];
                            return;
                        }
                    case 3:
                    case 5:
                    case 6:
                    case 7:
                    case 8:
                    case 9:
                    case 10:
                    case 11:
                    case 13:
                    case 17:
                    case 18:
                    case 19:
                    default:
                        break;
                    case 4:
                        if (this.ch == '"') {
                            this.sp = 0;
                            this.pos = this.bp;
                            this.scanString();
                            return;
                        }
    
                        if (this.ch >= '0' && this.ch <= '9') {
                            this.sp = 0;
                            this.pos = this.bp;
                            this.scanNumber();
                            return;
                        }
    
                        if (this.ch == '[') {
                            this.token = 14;
                            this.ch = this.buf[++this.bp];
                            return;
                        }
    
                        if (this.ch == '{') {
                            this.token = 12;
                            this.ch = this.buf[++this.bp];
                            return;
                        }
                        break;
                    case 12:  //默认传进来的的expect就是12,所以会走到这个分支里边,会根据json串的情况给token赋值不同的值
                        if (this.ch == '{') { 
                            this.token = 12;
                            this.ch = this.buf[++this.bp];
                            return;
                        }
    
                        if (this.ch == '[') {
                            this.token = 14;
                            this.ch = this.buf[++this.bp];
                            return;
                        }
                        break;
                    case 14:
                        if (this.ch == '[') {
                            this.token = 14;
                            this.ch = this.buf[++this.bp];
                            return;
                        }
    
                        if (this.ch == '{') {
                            this.token = 12;
                            this.ch = this.buf[++this.bp];
                            return;
                        }
                        break;
                    case 15:
                        if (this.ch == ']') {
                            this.token = 15;
                            this.ch = this.buf[++this.bp];
                            return;
                        }
                    case 20:
                        if (this.ch == 26) {
                            this.token = 20;
                            return;
                        }
                        break;
                    case 16:
                        if (this.ch == ',') {
                            this.token = 16;
                            this.ch = this.buf[++this.bp];
                            return;
                        }
    
                        if (this.ch == '}') {
                            this.token = 13;
                            this.ch = this.buf[++this.bp];
                            return;
                        }
    
                        if (this.ch == ']') {
                            this.token = 15;
                            this.ch = this.buf[++this.bp];
                            return;
                        }
    
                        if (this.ch == 26) {
                            this.token = 20;
                            return;
                        }
                }
    
                if (this.ch != ' ' && this.ch != '\n' && this.ch != '\r' && this.ch != '\t' && this.ch != '\f' && this.ch != '\b') {
                    this.nextToken();
                    return;
                }
    
                this.ch = this.buf[++this.bp];
            }
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140
    • 141
    • 142
    • 143
    • 144
    • 145
    • 146
    • 147
    • 148
    • 149
    • 150
    • 151
    • 152
    • 153
    • 154
    • 155

    在解析的主代码如下

    public Object parse(Object fieldName) {
            JSONLexer lexer = this.getLexer();
            switch (lexer.token()) {
                case 2:
                    Number intValue = lexer.integerValue();
                    lexer.nextToken();
                    return intValue;
                case 3:
                    Object value = lexer.decimalValue(this.isEnabled(Feature.UseBigDecimal));
                    lexer.nextToken();
                    return value;
                case 4:
                    String stringLiteral = lexer.stringVal();
                    lexer.nextToken(16);
                    if (lexer.isEnabled(Feature.AllowISO8601DateFormat)) {
                        JSONScanner iso8601Lexer = new JSONScanner(stringLiteral);
                        if (iso8601Lexer.scanISO8601DateIfMatch()) {
                            return iso8601Lexer.getCalendar().getTime();
                        }
                    }
    
                    return stringLiteral;
                case 6:
                    lexer.nextToken();
                    return Boolean.TRUE;
                case 7:
                    lexer.nextToken();
                    return Boolean.FALSE;
                case 8:
                    lexer.nextToken();
                    return null;
                case 9:
                    lexer.nextToken(18);
                    if (lexer.token() != 18) {
                        throw new JSONException("syntax error");
                    }
    
                    lexer.nextToken(10);
                    this.accept(10);
                    long time = lexer.integerValue().longValue();
                    this.accept(2);
                    this.accept(11);
                    return new Date(time);
                case 12:   //token就用在这里,可以看到这里就是调的parseObject
                    JSONObject object = new JSONObject();
                    return this.parseObject(object, fieldName);
                case 14: //这里就是调的parseArray
                    JSONArray array = new JSONArray();
                    this.parseArray(array, fieldName);
                    return array;
                case 20:
                    if (lexer.isBlankInput()) {
                        return null;
                    }
                case 5:
                case 10:
                case 11:
                case 13:
                case 15:
                case 16:
                case 17:
                case 18:
                case 19:
                default:
                    throw new JSONException("TODO " + lexer.tokenName() + " " + lexer.stringVal());
                case 21:
                    lexer.nextToken();
                    HashSet<Object> set = new HashSet();
                    this.parseArray(set, fieldName);
                    return set;
                case 22:
                    lexer.nextToken();
                    TreeSet<Object> treeSet = new TreeSet();
                    this.parseArray(treeSet, fieldName);
                    return treeSet;
            }
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
  • 相关阅读:
    【原创】辟谣,实测MyBatisPlus批量新增更新方法确实有效,且可单独使用无需跟随IService
    无缝滚动效果(鼠标移入暂停、单图暂停一段时间然后继续效果)
    【微服务|Sentinel】Sentinel快速入门|构建镜像|启动控制台
    RGB-T追踪——【综述】A Survey for Deep RGBT Tracking.
    外卖打印机wtn6040语音方案——让餐厅运营更高效
    mssql ,数据库还原BAK命令行方式
    python之正则表达式【简化版】
    案例分享|生产环境MQ集群一个非常诡异的消费延迟排查
    ModernCSS.dev - 来自微软前端工程师的 CSS 高级教程,讲解如何用新的 CSS 语法来解决旧的问题
    基于vue的实时交流聊天系统软件设计
  • 原文地址:https://blog.csdn.net/u013978512/article/details/133878810