我如何去设置的TextView当该字符串不是嵌入的资源显示UTF-8?字符串、不是、何去、资源

2023-09-06 10:38:16 作者:红杏想出墙

我遇到一个奇怪的情况,即我是从一个JSON文件获取字符串,我从具有西班牙字符,他们在我的TextViews正确显示我的资源XML文件加载,但琴弦,我在运行时通过HTTP加载显示丢失的char []盒

I'm encountering an odd situation whereby strings that I load from my resource XML file that have Spanish characters in them display correctly in my TextViews, but strings that I'm fetching from a JSON file that I load via HTTP at runtime display the missing char [] boxes

ESPAÑOL例如,嵌在我的XML字符串时工作正常,但是从我的JSON拉时呈现为SPAA [] OL,所以N是转变成一个又一个丢失字符!

ESPAÑOL for example, when embedded in my XML strings works fine, but when pulled from my JSON is rendered as SPAÃ[]OL, so the Ñ is transformed into a à and a missing char!

我不知道我在需要截取这些字符串,并设置正确的编码,他们什么时候。 JSON的文本文件本身是通过节点的服务器上生成的,因此,我不能完全肯定,如果这是在我应该编码,或者如果我要在Android上侧被编码的FileReader,或者设定点TextView的自己是一些特殊的编码类型(我不知道这是一种选择,只是有点扔我的手在空中,真的)的。

I'm not sure at what point I need to intercept these strings and set the correct encoding on them. The JSON text file itself is generated on the server via Node, so, I'm not entirely sure if that's the point at which I should be encoding it, or if I should be encoding the fileReader on the Android side, or perhaps setting the TextView itself to be of some special encoding type (I'm unaware that this is an option, just sort of throwing my hands in the air, really).

根据ianhanniballake的建议,我记录,看到了扭曲的字符实际上显示了在日志中也是如此。然而,当我看到了Android的文件系统上的一个文本阅读器JSON文件(它坐在SD卡),它似乎是正确的。

As per ianhanniballake's suggestion I am logging and seeing that the screwy characters are actually showing up in the log as well. However, when I look at the JSON file with a text viewer on the Android file system (it's sitting on the SDCARD) it appears correct.

推荐答案

所以,事实证明,文本文件,实际上是恩codeD正确,问题是,我没有设置UTF-8我上的FileInputStream编码...

So, it turned out that the text file was, indeed, encoded correctly and the issue was that I wasn't setting UTF-8 as my encoding on the FileInputStream...

的解决方案是正是如此读取文件:

The solution is to read the file thusly:

static String readInput() {
    StringBuffer buffer = new StringBuffer();
    try {
        FileInputStream fis = new FileInputStream("myfile.json");
        InputStreamReader isr = new InputStreamReader(fis, "UTF8");
        Reader in = new BufferedReader(isr);
        int ch;
        while ((ch = in.read()) > -1) {
            buffer.append((char) ch);
        }
        in.close();
        return buffer.toString();
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}