简体   繁体   English

如何使用GSON序列化UTF-8中的日语字符?

[英]How to serialize japanese chars in UTF-8 using GSON?

I am currently using a code (best answer on a question) I found here everything works properly until you give it a japanese String input. 我目前正在使用代码(问题的最佳答案)我在这里发现一切正常,直到你给它一个日语String输入。

I thought the UTF-8 charset would do the trick but I am not really sure what part of the code does not allow japanese characters to be serialized. 我认为UTF-8字符集可以解决问题,但我不确定代码的哪一部分不允许日文字符序列化。

For example if I serialize something basic like "ひらがな" it will output garbage characters. 例如,如果我序列化像"ひらがな"这样的基本内容,它将输出垃圾字符。

What I am doing is something like 我正在做的事情是这样的

String serialized = serialize("ひらがな");
String deserialized = deserialize(serialized, new TypeToken<String>() {}.getType());
System.out.println(deserialized);

But I am getting a garbage deserialized . 但我得到一个垃圾deserialized

Can someone please shed some light? 有人可以解释一下吗? Thank you. 谢谢。

I don't know the exact answer to your question, but I can say I had a similar problem and here was my solution. 我不知道你的问题的确切答案,但我可以说我有类似的问题,这是我的解决方案。 Maybe it's a hint for you: 也许这是对你的暗示:

I am only using GSON for deserialization. 我只使用GSON进行反序列化。 I had to change the following code from 我不得不更改以下代码

json = gson.fromJson(new InputStreamReader(is), parseType);

to

json = gson.fromJson(new InputStreamReader(is,"UTF-8"), parseType);

So the issue was in my input stream reader, not GSON per se. 所以问题出在我的输入流阅读器中,而不是GSON本身。 I wonder if you need to use a string reader for deserialization or something. 我想知道你是否需要使用字符串阅读器进行反序列化或其他东西。 Sorry I can't give you a more specific answer. 对不起,我不能给你一个更具体的答案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM