在json字符串转object类型的时候,报的错。

Unexpected character (“我得明天“,““(code 31070 / 0x795e))

Exception while XX方法 Unexpected character ('神' (code 31070 / 0x795e)): was expecting comma to separate Object entries
 at [Source:

看到json 字符串中出现了特殊字符“"”(英文的双引号)。

先转换成中文的双引号,然后去转换成object对象,后再replace成英文的双引号,借鉴了网上的方法。

public String toJsonStr(String s) {
        char[] tempArr = s.toCharArray();
        int tempLength = tempArr.length;
        for (int i = 0; i < tempLength; i++) {
            if (tempArr[i] == ':' && tempArr[i + 1] == '"') {
                for (int j = i + 2; j < tempLength; j++) {
                    if (tempArr[j] == '"') {
                        if (tempArr[j + 1] != ',' && tempArr[j + 1] != '}') {
                            tempArr[j] = '”'; // 将value中的 双引号替换为中文双引号
                        } else if (tempArr[j + 1] == ',' || tempArr[j + 1] == '}') {
                            break;
                        }
                    }
                }
            }
        }
        return new String(tempArr);
    }
String temp = "aaaa"d"cc";
String str= temp .replace('”','"');

因为没有好的捕获机制,才出现这个错,顺便加上trycatch捕获这个异常,

用e.printStackTrace(); 先把异常抛出来

com.fasterxml.jackson.core.JsonParseException: Unexpected character ('我' (code 31070 / 0x795e)): was expecting comma to separate Object entries
 try { 
         return true;
     }catch (JsonParseException ex){
            //去转换成中文的双引号,然后转换完object对象,再replace成英文的双引号
     } catch (JsonProcessingException e) {
           return false;
     }

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐