【问题标题】:UTF 8 decoding issue for json(using google gson) stringjson(使用google gson)字符串的UTF 8解码问题
【发布时间】:2014-10-24 21:01:15
【问题描述】:

我有 Spring 控制器方法,它使用 Google.Gson 返回 json 字符串。问题是,我的 json 字符串包含 UTF-8 内容,当我从浏览器访问 url 时,它会以编码格式显示数据。

@ResponseBody
@RequestMapping(value="/getLocations.json", method = RequestMethod.GET)
public String getLocations(HttpServletRequest request,HttpServletResponse response)throws Exception {
   Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().serializeNulls().create();
    response.setContentType("application/json; charset=utf-8");
    Set<Locations> locs = channelService.getLocations();
    String json = gson.toJson(locs);        
    return json;
}

当我从下面的浏览器地址栏中访问 getLocations.json 时,我得到的是:

[{"id":1,"name":"\u0026#3248;\u0026#3262;\u0026#3255;\u0026#3277;\u0026#3231;\u0026#3277;\u0026#3248;\u0026#3264;\u0026#3247;"},{"id":2,"name":"Districts"}]

知道我要去哪里穿吗?或者我怎样才能将数据解码回来?

【问题讨论】:

  • 尝试删除charset=utf-8
  • @ankur-singhal,还是一样

标签: java json spring-mvc utf-8 gson


【解决方案1】:

试试这个

var uri = "http://w3schools.com/my test.asp?name=ståle&car=saab";
var uri_enc = encodeURIComponent(uri);
var uri_dec = decodeURIComponent(uri_enc);
var res = uri_enc + "<br>" + uri_dec; 


http%3A%2F%2Fw3schools.com%2Fmy%20test.asp%3Fname%3Dst%C3%A5le%26car%3Dsaab     // Encoded URI
http://w3schools.com/my test.asp?name=ståle&car=saab                            // Decoded URI

解码后,尝试解析json

var json = '{"result":true,"count":1}',
    obj = JSON.parse(json);

【讨论】:

    猜你喜欢
    • 2018-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-15
    • 2015-05-09
    • 2022-11-12
    • 2018-06-29
    相关资源
    最近更新 更多