xuminwlt 2012-08-21 11:50
浏览 347
已采纳

Struts2返回到浏览器的Json的文本格式一直带转义过的双引号和反斜杠

Struts2里面的Action对象的result的String Print出来的结果没有问题
{"id":"4028efd439422d260139422d2a530000","name":"department"}

在Struts.xml里面配置的



result



然后再浏览器中输入对应的地址调用
返回的结果是:
"{\"id\":\"4028efd439422d260139422d2a530000\",\"name\":\"department\"}"

说明返回成果,但是文本的格式我用Jquery 的json完全不能解析这样子格式的对象,如果当做string类型来拆分过滤掉引号和反斜杠岂不有些多此一举,我只能想象可能是我哪里没有设置什么,请大家过目。

在$.ajax中返回的的是正在的JSON格式的对象,我认为是在最后的输出过程中做了一次我不想要的转义,求解。
例如:
JSONUtil.serialize(obj.toString());

我只想在浏览器中得到这样子的结果
{"id":"4028efd439422d260139422d2a530000","name":"department"}

  • 写回答

5条回答 默认 最新

  • jinnianshilongnian 2012-08-21 14:15
    关注

    你可以看一下jQuery内部实现:

    [code="java"]parseJSON: function( data ) {
    if ( typeof data !== "string" || !data ) {
    return null;
    }

        // Make sure leading/trailing whitespace is removed (IE can't handle it)
        data = jQuery.trim( data );
    
        // Make sure the incoming data is actual JSON
        // Logic borrowed from http://json.org/json2.js
        if ( /^[\],:{}\s]*$/.test(data.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, "@")
            .replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, "]")
            .replace(/(?:^|:|,)(?:\s*\[)+/g, "")) ) {
    
            // Try to use the native JSON parser first
            return window.JSON && window.JSON.parse ?
                window.JSON.parse( data ) :
                (new Function("return " + data))();
    
        } else {
            jQuery.error( "Invalid JSON: " + data );
        }
    },[/code]
    

    1、如果你有JSON parse 就用它来进行解析:[url]http://www.json.org/js.html[/url]
    2、否则 (new Function("return " + data))();

    这里注意data一定是字符串的,也就是说struts2传给前端的数据没有错,你要认识到这点;

    eval函数是浏览器内置的,它可以编译和执行任何javascript代码,因此相对来说不太安全,因此jQuery没有使用的:
    [quote]The eval function is very fast. However, it can compile and execute any JavaScript program, so there can be security issues. [/quote]

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?