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


发现问题

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

调查问题

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

    public static void writeJSONString(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;
            else
                out.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中的斜杠(还包含其他很多字符)转义了,在前面自动加上了反斜杠,问题根源找到。

解决方案

特别说明

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

相关内容