请帮我在Java的属性文件中按原样读取UNICODE字符。例如:如果我传递键“Account.label.register”,它应该返回“\u5BC4\u5B58\u5668”,而不是其字符表示,如“寄存器”。以下是我的样例属性文件:
然而,如果“错误”包含中文文本,例如:“无效的代码”
响应:
由于中文文本为空,我考虑通过X-JSON标头发送Unicode,如下所示。
file_ch.properties
Account.label.register = \u5BC4\u5B58\u5668
Account.label.login = \u767B\u5F55
Account.label.username = \u7528\u6237\u540D
Account.label.password = \u5BC6\u7801
谢谢。
你好,我正在使用以下Java代码读取属性文件:
@Override
public ResourceBundle getTexts(String bundleName) {
ResourceBundle myResources = null;
try {
myResources = ResourceBundle.getBundle(bundleName, getLocale());
} catch (Exception e) {
myResources = ResourceBundle.getBundle(getDefaultBundleKey(), getLocale());
}
return myResources;
}
使用上述方法是可以的,我能得到中文字符。但是对于我应用程序中的一些ajax请求,我需要在X-JSON标题中传递中文文本。下面给出示例代码:
HashMap<String, List<String>> map = new HashMap<String, List<String>>();
List<String> errors = new ArrayList<String>();
errors.add(str); /*ex: str = "无效的代码" , value taken from properties file through resource bundle*/
map.put("ERROR", errors);
JSONObject json = JSONObject.fromObject(map);
response.setCharacterEncoding("UTF-8");
response.setHeader("X-JSON", json.toString());
response.setStatus(500);
我正在传递英语例子str="Invalid Code",X-JSON标头携带信息如原样。但是,如果str="无效的代码"(中文或其他任何文本),X-JSON标头会像下面的响应一样携带空文本:
response :
connection:close
Content-Encoding:gzip
Content-Type:text/html;charset=UTF-8
Date:Wed, 08 Jun 2016 10:17:43 GMT
Server:Apache-Coyote/1.1
Transfer-Encoding:chunked
Vary:Accept-Encoding
X-JSON:{"ERROR":["Invalid Code"]}
然而,如果“错误”包含中文文本,例如:“无效的代码”
响应:
connection:close
Content-Encoding:gzip
Content-Type:text/html;charset=UTF-8
Date:Wed, 08 Jun 2016 10:17:43 GMT
Server:Apache-Coyote/1.1
Transfer-Encoding:chunked
Vary:Accept-Encoding
**X-JSON:{"ERROR":[" "]}** /*expecting the response X-JSON:{"ERROR":["无效的代码"]}*/
由于中文文本为空,我考虑通过X-JSON标头发送Unicode,如下所示。
{"ERROR":["\u65E0\u6548\u7684\u4EE3\u7801"]}
在评估X-JSON标头后,希望使用JavaScript代码解析Unicode字符,如下所示:
var json;
try {
json = xhr.getResponseHeader('X-Json');
} catch (e) {
alert(e);
}
if (json) {
var data = eval('(' + json + ')');
decodeMsg(data);
}
function decodeMsg(message) {
var mssg = message;
var r = /\\u([\d\w]{4})/gi;
mssg = mssg.replace(r, function (match, grp) {
return String.fromCharCode(parseInt(grp, 16)); } );
mssg = unescape(mssg);
return mssg;
}
请提出建议。谢谢。