将UTF-8上的ASCII文字字符转换为特殊字符

时间:2018-04-23 16:13:29

标签: java json string character-encoding special-characters

我在网上发现了数以千计的类似问题,但没有一个问题我有同样的问题。

我正在使用第三方json web api,但回答的json有时会在HTTP上错误地打印特殊字符

ex:{"message": "Usu\u00e1rio n\u00e3o encontrado", "status": "fail"}

它应该是:{"message": "Usuário não encontrado", "status": "fail"}

我无法控制后端api,我已经尝试了一切告诉服务器回答我UTF-8,我的请求有标题:

Accept: */*;charset=UTF-8
Accept-Charset: UTF-8

但是服务器一直在回答错误的字符...... 所以我试着阅读原始的http响应并自行解码

byte[] temp = resp.errorBody().bytes();
errorResponse = new String(temp);
errorResponse = new String(temp,"UTF-8");
errorResponse = new String(temp,"iso-8859-1");
errorResponse = new String(temp,"US-ASCII");
errorResponse = new String(temp,"windows-1252");
errorResponse = new String(temp,"Windows-1251");
errorResponse = new String(temp,"GB2312");
errorResponse = new String(temp,"ISO-8859-2");
errorResponse = new String(temp,"Windows-1250");

我已经对这段代码进行了调查,并检查了新的断言是否仍然存在错误的字符。

所以我相信后端服务器会生成一个iso-8859-1字符串,并在UTF-8 http主体上打印它。

再说一遍:我无法控制后端代码,有什么办法可以在客户端修复这个字符串吗?

1 个答案:

答案 0 :(得分:2)

这只是一个想法,但我觉得你的服务器实际上发送了这些字符:

\
u
0
0
e
1

而不是“á”。所以我写了下面的原型,我不得不说这绝对不是生产质量代码。但是,如果您将服务器中的JSON提供给它,您能尝试一下吗?

package com.severityone.test;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CharTest {

    public static void main(final String... args) {

        final String json = "{\"message\": \"Usu\\u00e1rio n\\u00e3o encontrado\", \"status\": \"fail\"}";
        final Matcher matcher = Pattern.compile("\\\\u([0-9a-z]{4})").matcher(json);
        final StringBuffer result = new StringBuffer();
        while (matcher.find()) {
            matcher.appendReplacement(result, String.format("%c", Integer.valueOf(matcher.group(1), 16)));
        }
        matcher.appendTail(result);
        System.out.println(result.toString());
    }
}

该程序给出以下结果:

{"message": "Usuário não encontrado", "status": "fail"}
相关问题