码迷,mamicode.com
首页 > Web开发 > 详细

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

时间:2015-05-05 21:55:19      阅读:200      评论:0      收藏:0      [点我收藏+]

标签:json

发现问题

最近写了个程序,在构建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中的斜杠(还包含其他很多字符)转义了,在前面自动加上了反斜杠,问题根源找到。

解决方案

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

特别说明

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

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

标签:json

原文地址:http://blog.csdn.net/winwill2012/article/details/45507715

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!