在项目中使用了文本编辑器,在做添加和修改操作时,经常会把各个输入表单域的值组装成json,然后使用ajax进行form表单提交。而文本编辑器提交的值是html标签的格式:如下:

<p style="font-size:20px;">你好,&nbsp;</p>

在提交到服务器使用JSONObject.fromObject(param)时会报

net.sf.json.JSONException: Unterminated string at character 38 of

错误,解决该方法,我是这样做的。虽然提交到后台的数据是html标签格式的,在调用JSONObject.fromObject(param)之前,通过转换处理<,>和单引号和双引号等特殊字符,然后Post到服务器后,再解码成正常的,然后继续保存或修改到数据库里。

/*3.用正则表达式实现html转码*/
    private String  htmlEncodeByRegExp(String str){
        String s = "";
        if(str.length() == 0) return "";
        s = str.replace("&","&amp;");
        s = s.replace("<","&lt;");
        s = s.replace(">","&gt;");
        s = s.replace("'","&#39;");
        s = s.replace("\"","&quot;");
        s = s.replace("\n","\\\\n");
        s = s.replace("\r","\\\\r");
        return s;
    }
/*4.用正则表达式实现html解码*/
    private String htmlDecodeByRegExp (String str){
        String s = "";
        if(str.length() == 0) return "";
        s = str.replace("&amp;","&");
        s = s.replace("&lt;","<");
        s = s.replace("&gt;",">");
        s = s.replace("&nbsp;"," ");
        s = s.replace("&#39;","\'");
        s = s.replace("&quot;","\"");
        s = s.replace("\\n", "\n");
        s = s.replace("\\r", "\r");
        return s;
    }

这样就绕开了JSON转换的错误,我也是网上找到的方法,希望对各位小伙伴有所帮助!