首页 > 解决方案 > 将 PHP 发送的 JSON 字符串中的欧元符号转换为 Java 字符串 (utf-8)

问题描述

我正在构建一个打印到热敏打印机的Android€应用程序,但打印符号有问题。

具体来说,我的 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

标签: javaphpandroid

解决方案


我通过使用以下代码解决了它:

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.(阿曼里亚尔货币符号)将不起作用,除非您使用数组并解析每个等.) 但至少它是一个开始。谢谢!


推荐阅读