java - 将 PHP 发送的 JSON 字符串中的欧元符号转换为 Java 字符串 (utf-8)
问题描述
我正在构建一个打印到热敏打印机的Android€
应用程序,但打印符号有问题。
具体来说,我的 Android 应用程序:
- 向 php 文件发出GET请求
- php 文件构建一个JSON对象
- 我的 JSON 值之一包含"\u20AC",即 unicode 中的欧元符号。
- php 文件对 JSON 进行字符串化 + 将其发送回Android
它发送UTF-8编码的数据(纯文本)
我的 PHP 发回代码基本上是这样的:
header("Content-Type: text/html; charset=UTF-8\n");
...
$currency_symbol = '\u20AC';
...
$blah = array("id"=>$order['id'], ... , "currency_symbol"=> $currency_symbol);
echo json_encode( $blah );
exit;
在此之前,我可以通过以下方式将€符号打印到打印机:
- 更改为正确的热敏打印机代码页
- 调用以下代码:
new String("\u20ac").getBytes( Charset.forName("Windows-1252") ) );
然后将euro
字节直接发送到打印机。
With JSON solution, i can not render the euro sign anymore as every try, even the previous working one, it always renders this to printer (but not the sign):
\u20AC
PS。我对其他 UTF-8 字符串没有任何问题,因为我可以通过以下方式打印它们:
String.format("- " + json_obj.getString("address") + "\n").getBytes( charset )
json_obj
来自 PHP 的编码 JSON 和打印机设置为的代码页中的字符集在哪里(as )Charset
。
解决方案
我通过使用以下代码解决了它:
String currency_symbol_hex = order_obj.getString("currency_symbol");
String currency_symbol_str = Character.toString((char) Integer.parseInt(currency_symbol_hex,16));
BT_write( String.format("%s", currency_symbol_str).getBytes( Charset.forName("Windows-1252") ) );
其中order_obj.getString("currency_symbol")
是 PHP 发送的 JSON 值,仅包含20AC
(而不是\u20AC
),并且BT_write
基本上将字节写入连接的蓝牙套接字。
像这样currency_symbol
存储在 JSON 中:
return array(
...
"euro"=>array("symbol"=>"€","symbol_unicode"=>"20AC")
-------^
...
);
我只是通过currency_symbol
我的 JSON 中的密钥返回它。
这显然不是最好的解决方案,因为不同的货币可能需要不同的字符集,Windows-1252
并且还需要 PHP 端的特殊情况(发送 2 个 unicode 代码,例如\u0631.\u0639.
(阿曼里亚尔货币符号)将不起作用,除非您使用数组并解析每个等.) 但至少它是一个开始。谢谢!
推荐阅读
- sql - 由于帐户重复的问题,Oauth2 是否比它的价值更麻烦?
- python - 创建 CSV 文件,然后使用 boto3 附加到电子邮件
- jquery - 如何在 asp.net web 表单中使用带有 html 选择控件的 Select2 jQuery 插件?
- javascript - 复选框在html中无法正常工作如何解决?
- r - R foreach do parallel 在循环完成后不会结束
- javascript - 使用 Vanilla JavaScript 访问 Index(i) 将 Click 事件添加到 for 循环中的每个项目
- reactjs - 得到响应:“INVALID_ARGUMENT: Project id 'X' , is malformed
- android - Android SDK工具+Flutter:正确的目录结构和环境变量
- javascript - 即使表达式为真,NgIf 也不显示
- linux-kernel - Yocto Patch Linux Kernel In-Tree-Module,带有从 Out-Of-Tree 模块导出的外部符号