當Emoji表情字符存儲有問題,或者遇到保存字符串到數據庫裏出現\xF0\x9F\x92\x94類似問題時,請嘗試使用這個工具。
什麼工具呢?
Java Emoji Converter 。
GitHub地址爲:https://github.com/binarywang/java-emoji-converter
可以將Emoji表情(
)轉義成**沉默王二😊**這樣的。
那,該怎麼使用這款工具呢?
首先,在pom.xml文件中引入jar包:
<dependency>
<groupId>com.github.binarywang</groupId>
<artifactId>java-emoji-converter</artifactId>
<version>0.1.1</version>
</dependency>
然後,在Java類中聲明一個EmojiConverter,如下:
private EmojiConverter emojiConverter = EmojiConverter.getInstance();
使用方法也非常簡單,如下:
String str = " An ����awesome ����string with a few ����emojis!";
String alias = this.emojiConverter.toAlias(str);
String html = this.emojiConverter.toHtml(str);
toAlias將Emoji轉義爲關鍵字,類似:xiao:。
toHtml將Emoji轉義爲unicode,類似?。
可以直接將toHtml轉換後的字符串保存到數據庫,顯示的時候,就直接顯示,不需要再轉義,HTML是支持的。整體代碼實例如下:
package com.comwer;
import com.github.binarywang.java.emoji.EmojiConverter;
import junit.framework.Assert;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
/**
* Unit test for simple App.
*/
public class AppTest extends TestCase {
private EmojiConverter emojiConverter = EmojiConverter.getInstance();
/**
* Create the test case
*
* @param testName
* name of the test case
*/
public AppTest(String testName) {
super(testName);
}
/**
* @return the suite of tests being tested
*/
public static Test suite() {
return new TestSuite(AppTest.class);
}
/**
* Rigourous Test :-)
*/
public void testApp() {
String str = " An ����awesome ����string with a few ����emojis!";
String alias = this.emojiConverter.toAlias(str);
String html = this.emojiConverter.toHtml(str);
System.out.println(str);
System.out.println(html);
System.out.println("EmojiConverterTest.testToAlias()=====>");
System.out.println(alias);
Assert.assertEquals(
":no_good: :ok_woman: :couple_with_heart:An :smiley::grinning:awesome :smiley::smiley:string with a few :smiley::wink:emojis!",
alias);
assertTrue(true);
}
}
這種方法的最大好處就是數據庫的編碼還是utf-8,而不必改成utf8mb4。強烈推薦。
lib包地址:
https://www.baidu.com/link?url=kxuz4GCJKAVkMCT1DfNMotOnrLrVl-8f3qx109Z97QVsZT7rugsOM0VDtas0sESKyihKwO9JoDsdPCHLMzaHmZEq9VpXstCT15aZgpFKEpeWGUye2hBgna_VFccw6tJH&wd=&eqid=cb308fe50004ab23000000065da41f5b
https://blog.csdn.net/qing_gee/article/details/80097901