解析错误富文本json字符串(带双引号)的解决办法
公司的项目,通过json传回来的是这么个东西:
NewsId":"94f52614-8764-46d7-a5fe-d0da1fe878ed","NewsTitle":"大型公选课《可持续发展与未来》系列二之现代经济(绿色经济)开始网上选课报名","NewsContent":"<span style="font-size:12pt;font-family:宋体;color:black;line-height:150%;"><span>近日,伴随着我校郑时龄院士、童小华教授分别在四平、嘉定举行的精彩演讲,本学期我校着力打造的大型公共选修课程《可持续发展与未来》之系列一已经圆满结束。该课程也是我校</span>“<span>可持续发展辅修专业</span>”<span>的核心必修课程之一。</span></span> <p style="text-indent:21pt;"> </p>......... </span>
各种查询之后发现无法解析的根本原因就是里面有双引号" " "和反斜杠" ".
还不能直接对json进行转义,否则会将json本身自带的双引号都给转义了,所以不能暴力转义
上网找的方法:
//将坏的json数据里面的双引号,改为中文的双引号(啥都行,只要不是双引号就行)
public String jsonStringConvert(String s){
char[] temp = s.toCharArray();
int n = temp.length;
for(int i =0;i<n;i++){
if(temp[i]==":"&&temp[i+1]=="""){
for(int j =i+2;j<n;j++){
if(temp[j]=="""){
if(temp[j+1]!="," && temp[j+1]!="}"){
temp[j]="”";
}else if(temp[j+1]=="," || temp[j+1]=="}"){
break ;
}
}
}
}
}
return new String(temp);
}</span>
此方法能将json本身的双引号以外的双引号转义为中文的双引号(其他什么都行)。这样就能够转义为正确的json字符串。
bingo
备忘:
在此方法之前,还要将html代码去空格,否则json也不能够解析,去空格方法:
public String replaceBlank(String str) {
String dest = "";
if (str != null) {
Pattern p = Pattern.compile("\s*| |
|
");
Matcher m = p.matcher(str);
dest = m.replaceAll("");
// Pattern p2 = Pattern.compile("\s*"");
// Matcher m2 = p2.matcher(dest);
// dest = m2.replaceAll(""");
dest = dest.replace("="", "="");
p = Pattern.compile("" *>");
m = p.matcher(dest);
dest = m.replaceAll(">"");
}
return dest;
}</span>
参考文献:
http://bbs.csdn.net/topics/390578406?page=1
http://www.eoeandroid.com/thread-558180-1-1.html
http://www.cnblogs.com/catprayer/archive/2012/10/09/2716962.html
声明:该文观点仅代表作者本人,入门客AI创业平台信息发布平台仅提供信息存储空间服务,如有疑问请联系rumenke@qq.com。
- 上一篇:没有了
- 下一篇:没有了
