最近做一个android新闻客户端 ,需要解析接口数据,格式json。 但是数据源中含有双引号 ,导致fastjson ,gson等都解析失败
如下:
{"result":{"stat":"200","remark":"成功"},
"data":{"news":[
{"id":"104773","title":"黄湖一孤寡老人一次缴20000元党费"},
{"id":"112324","title":"余杭花费3亿回购28家卫生院 "医改"让百姓得到实惠"},
{"id":"112329","title":"余杭卫生院7年后纠错回购 7500万卖出3亿买回"},
{"id":"119324","title":"余杭黄湖镇3000多平方米厂房出租或转让"},
{"id":"119335","title":"余杭黄湖镇百丈镇一夜16辆车被撬"},
{"id":"407788","title":"黄湖镇召开城管工作会议"},
{"id":"407767","title":"普及急救知识 提高急救水平"},
{"id":"407775","title":"深化党内民主 完善自身建设 "},
{"id":"407793","title":"副区长阮英调研黄湖镇旅游产业发展和养老设施项目建设情况"}
]
}
}
"news" 第二条数据 ,titile值中带有双引号,破坏了json格式 ,导致无法解析
百度了下 ,没有找到合适的解决方案,又不能让接口方做调整,所以自己试着处理了下 ,把属性值中的英文双引号变换成中文的双引号
代码如下:
private static String jsonString(String oldJson) {
char[] temp = oldJson.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);
}
处理后顺利将属性值中的英文双引号变成中文双引号:
{"result":{"stat":"200","remark":"成功"},
"data":{"news":[
{"id":"104773","title":"黄湖一孤寡老人一次缴20000元党费"},
{"id":"112324","title":"余杭花费3亿回购28家卫生院 “医改”让百姓得到实惠"},
{"id":"112329","title":"余杭卫生院7年后纠错回购 7500万卖出3亿买回"},
{"id":"119324","title":"余杭黄湖镇3000多平方米厂房出租或转让"},
{"id":"119335","title":"余杭黄湖镇百丈镇一夜16辆车被撬"},
{"id":"407788","title":"黄湖镇召开城管工作会议"},
{"id":"407767","title":"普及急救知识 提高急救水平"},
{"id":"407775","title":"深化党内民主 完善自身建设 "},
{"id":"407793","title":"副区长阮英调研黄湖镇旅游产业发展和养老设施项目建设情况"}
]
}
}
gson顺利解析成功 。
如果json数据中还包含其他不规范的符号 , 可以同时过滤掉 , 如下:
private static String jsonString(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;
}
} else if (temp[j] == '-') {
temp[j] = ' ';
} else if (true) {
// 要过虑其他字符,继续添加判断就可以
}
}
}
}
return new String(temp);
}