使用simple json时遇到的一个小问题

发现问题

最近写了个程序,在构建http参数的时候使用到了org.json.simple.JSONObject这个类,上线之后有客户反馈说http参数格式不正确,如果参数中包含斜杠(/)则前面都会自动加上一个反斜杠()。

调查问题

发现问题之后首先去看了一下simple json的源代码,在他的源码中发现如下一段:

(Map map, Writer out) throws IOException {if(map == null){out.write(“null”);return;}boolean first = true;Iterator iter=map.entrySet().iterator();out.write(‘{‘);while(iter.hasNext()){if(first)first = false;elseout.write(‘,’);Map.Entry entry=(Map.Entry)iter.next();out.write(‘\”‘);out.write(escape(String.valueOf(entry.getKey())));out.write(‘\”‘);out.write(‘:’);JSONValue.writeJSONString(entry.getValue(), out);}out.write(‘}’);}public String toString(){return toJSONString();}/*** Escape quotes, \, /, \r, \n, \b, \f, \t and other control characters(U+0000 through U+001F).* It’s the same as JSONValue.escape() only for compatibility here.** @see org.json.simple.JSONValue#escape(String)** @param s* @return*/public static String escape(String s){return JSONValue.escape(s);}

从中可以知道,,simple json在序列化的时候已经将string中的斜杠(还包含其他很多字符)转义了,在前面自动加上了反斜杠,问题根源找到。

解决方案使用正则表达式替换一下simple json toString()之后的字符串,将不希望转义的字符恢复原型;使用其他json库,比如org.json.JSONObject,这个库不会自动转义。特别说明

其实国际规范中json中的key和value的字符串中包含的斜杠是需要转义的,只是转义之后在笔者的使用场景下会出错,特此说明。ECMA-404 json标准

我没有值得分享的感伤爱情故事,

使用simple json时遇到的一个小问题

相关文章:

你感兴趣的文章:

标签云: