java emoji emoji storage solution

  • 2020-08-22 21:58:19
  • OfStack

1. Problems

The problem I encountered was that some useful avatals used WeChat's emoji emoticons when developing WeChat, but my mysql database used the code utf8_general_ci, which is the code of utf-8, and the result reported an error.

2. Why does this happen

Because mysql's utf8 encodes a maximum of three bytes per character, but an emoji emoji is four bytes, utf8 does not support the storage of emoji emojis. But utf8's superset, utf8mb41, can contain up to 4 bytes of characters, so it supports the storage of emoji emojis.

3. Solution 1

Set your database codeset to utf8mb4, either database, table, or field. Although it will increase the storage, this is negligible.

4. Solution 2

As the saying goes, when the problem comes, either solve it or compromise it. If for some reason you can't change the database code or anything like that, you can use one of java's add-ons, such as ES37en-ES38en, to make special changes to the emojis and then save or remove the emojis, which is another solution.

5. What do you say at the end

After thinking about a problem from different angles, it turns out that the world is the same but different, different but the same...

Finally, a piece of code:


import com.github.binarywang.java.emoji.EmojiConverter;


/**
 *  Expression processing class 
 * @author Administrator
 *
 */
public final class EmojiUtil {

  private static EmojiConverter emojiConverter = EmojiConverter.getInstance();
  
  /**
   *  will emojiStr to   An emotive character 
   * @param emojiStr
   * @return
   */
  public static String emojiConverterUnicodeStr(String emojiStr){
     String result = emojiConverter.toUnicode(emojiStr);
     return result;
  }
  
  /**
   *  A string with an expression is converted to an encoding 
   * @param str
   * @return
   */
  public static String emojiConverterToAlias(String str){
    String result=emojiConverter.toAlias(str);
    return result;
  }
  
  
}

The framework used is:


<dependency>
  <groupId>com.github.binarywang</groupId>
  <artifactId>java-emoji-converter</artifactId>
  <version>0.0.1</version>
</dependency>

Related articles: