特殊表情存数据库处理

开发途中遇到评价的功能,需要存入表情符号比如:

以及这种

存入数据库的时候会抛出异常,\x86\啥的

百度解决办法是 数据库改utf8mb4  但是测试改表的字符集并没有用,

然后我也没敢改库的字符集仍然使用utf8

我的解决办法是代码层面的处理,进行URLEncoder转码 和URLEncoder 解码:

/**
	 * @Description emoji表情转换
	 * @param str 待转换字符串
	 * @return 转换后字符串
	 * @throws UnsupportedEncodingException
	 */
	public static String emojiConvertToUtf(String str)
			throws UnsupportedEncodingException {
		String patternString = "([\\x{10000}-\\x{10ffff}\ud800-\udfff])";

		Pattern pattern = Pattern.compile(patternString);
		Matcher matcher = pattern.matcher(str);
		StringBuffer sb = new StringBuffer();
		while (matcher.find()) {
			try {
				matcher.appendReplacement(
						sb,
						"[[" + URLEncoder.encode(matcher.group(1),
								"UTF-8") + "]]");
			} catch (UnsupportedEncodingException e) {
				throw e;
			}
		}
		matcher.appendTail(sb);
		log.info("emoji表情转字符串:"+sb.toString());
		return sb.toString();
	}

	/**
	 * @Description 还原emoji表情的字符串
	 *
	 * @param str 转换后的字符串
	 * @return 转换前的字符串
	 * @throws UnsupportedEncodingException
	 */
	public static String utfemojiRecovery(String str)
			throws UnsupportedEncodingException {
		String patternString = "\\[\\[(.*?)\\]\\]";

		Pattern pattern = Pattern.compile(patternString);
		Matcher matcher = pattern.matcher(str);

		StringBuffer sb = new StringBuffer();
		while (matcher.find()) {
			try {
				matcher.appendReplacement(sb,
						URLDecoder.decode(matcher.group(1), "UTF-8"));
			} catch (UnsupportedEncodingException e) {
				throw e;
			}
		}
		matcher.appendTail(sb);
		log.info("字符串转emoji表情:"+sb.toString());
		return sb.toString();
	}

注意:

测试时在对象get set方法上转码 解码,存入数据库仍然是失败的

大概是因为mybatis的insert 和 update方法 mapper快捷方法实际处理时仍存入的未转码的

所以在业务代码上进行转码解码的:

 /**
    * 转码  解决表情问题
    */
    try {
        evaluateContent = StringUtil.emojiConvertToUtf(evaluateContent);
    } catch (UnsupportedEncodingException e) {
     throw new BusinessException(CommonErrorCode.E_102906);
      }

 

 /**
             * 解码
             */
            try {
                evaluateContent = StringUtil.utfemojiRecovery(evaluateContent);
            } catch (UnsupportedEncodingException e) {
                throw new BusinessException(CommonErrorCode.E_102906);
            }

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值