Jstree,JSON_DATA插件和特殊字符

时间:2012-07-23 08:42:36

标签: json character-encoding jstree

我的页面上有一个jstree树结构,它使用JSON数据和AJAX。有一些斯堪的纳维亚字符(ä和ö),处理不当。

Jstree通过Java servlet过滤器获取JSON结构。该结构编码为UTF-8。当我用firebug查看返回的JSON结构时,斯堪的纳维亚字符会正确显示。我尝试将字符编码更改为ISO 8859-4只是为了看它是否有帮助,但事实并非如此。

我不确定代码的哪些部分与此问题相关,但这里有一些部分。

初始化树:

.jstree({   
    "json_data" : {
        "ajax" : {
            "url" : hostUrl+"/json/getAreaTree?treeType=Areas",
            "data" : function (n) {
                    return { id : n.attr ? n.attr("id") : 0 };
                }
        }
    },

一些servlet过滤器代码:

protected class GetAreaTreeContext extends ActionContext implements StreamResponseContext{

    private byte[] bytes;

    public GetAreaTreeContext() {
        super("getAreaTree");
    }

    @Override
    public byte[] getBytes() {
        return this.bytes;
    }

    @Override
    public String getContentType() {
        return "application/json; charset=UTF-8";
    }

    @Override
    protected boolean doAction() {
        if (!getWebSessionObject().isValid())
            return false;
        Map<String,Object> p = getParameterMap();
        String type = (String)p.get("treeType");
        String id = (String)p.get("id");
        if(id.equals("1") || id.equals("0") || id.equals("id1") || id.equals("id0")){ //get the tree only if request comes from initial situation (id=0) or the root (id=1)
            try {
                this.bytes = ObjectFactory.getInstance().getDbManager().getAreaFolderTree(type, phone).getBytes();
            } catch (Exception ex) {
                this.result = "";
            }
            return bytes.length > 0;
        }else{
            //init the array again so that when empty folders make ajax requests, they dont get the tree
            this.bytes = new byte[0];
            return true;
        }
    }

}

如何获取jstree JSON_DATA插件来处理UTF-8编码的斯堪的纳维亚字符?

1 个答案:

答案 0 :(得分:0)

我今天遇到了这个问题。即使我在(Safari)调试器中检查节点时看到JSON中为数据回调返回Øst,它也会呈现为�st。但是,Ricola3D的建议对我有用。我将Content-Type: application/json;charset=UTF-8添加到响应标头中,并立即清除渲染。

YMMV:我们的服务器端堆栈是Clojure + Ring,代理Apache,而Content-Type标头似乎确实影响从服务器返回的编码,来自Ring或底层jetty层。我坦率地不确定添加内容类型标头是否会更改浏览器中的JSON解析器如何解码响应主体,或者更改响应主体在Web服务器中的编码方式。