fastJson、jackJson遇到的坑,异常: JSON parse error: Cannot deserialize instance of `java.util.ArrayList` out

标题 JSON parse error: Cannot deserialize instance of java.util.ArrayList out of START_OBJECT token; nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of java.util.ArrayList out of START_OBJECT token

前端代码:

        //解析内容序列化
        var personJson = $("#frm1").serializeObject();
        var arr = Object.keys(personJson);
        if (arr.length != 0) {
            formData.personList = personArr;
        }
        Ajax.post({
                    url: 'info/item/add',
                    data: JSON.stringify(formData),
                    success: function (result) {
                        Dialog.msg("添加成功!");
                        window.location.href = "#info/item_list";
                    }
                });

之前用的是fastJson,没有问题,后面同事改代码加了jackJson,用于redis和elasticsearch的实体序列化,导致很多地方就会出现异常

org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot deserialize instance of `java.util.ArrayList` out of START_OBJECT token; nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `java.util.ArrayList` out of START_OBJECT token
 at [Source: (PushbackInputStream); line: 1, column: 15] (through reference chain: cn.ymcd.nimwp.info.dto.InfoItemDto["personList"])

后面看分析了问题之后,找到了解决办法:
修改前端代码


        var formData = $('#add_form').serializeJSON();
        //formData.type = $("#type").val();
        //解析内容序列化
        var personJson = $("#frm1").serializeObject();
        var arr = Object.keys(personJson);
        var jsonString = JSON.stringify(personJson);
        var personArr =  [];
        personArr.push(jsonString);
        if (arr.length != 0) {
            formData.personList = personJson;
        }

这个时候后端的到了后端又报错:

com.alibaba.fastjson.JSONException: illegal identifier

需要StringEscapeUtils 类进行转义和反转义代码:

//处理解析内容
        List personList = infoitemDto.getPersonList();
        if (!ChkUtil.isEmpty(personList)) {
            String json = StringEscapeUtils.unescapeHtml4(personList.get(0));
            JSONObject jsonObject = JSONUtils.parseObject(json);
            .........

这样就把问题解决了,做个记录分享下。

你可能感兴趣的:(fastJson、jackJson遇到的坑,异常: JSON parse error: Cannot deserialize instance of `java.util.ArrayList` out)