接口返回的 json数据中含有双引号 或其他非法字符的解决办法

最近做一个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);
	}


评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值