JacksonStringUnicodeSerializer.java 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. package com.emato.common.utils.oms;
  2. import com.fasterxml.jackson.core.JsonGenerator;
  3. import com.fasterxml.jackson.core.JsonParseException;
  4. import com.fasterxml.jackson.core.JsonProcessingException;
  5. import com.fasterxml.jackson.core.io.CharTypes;
  6. import com.fasterxml.jackson.core.json.JsonWriteContext;
  7. import com.fasterxml.jackson.databind.JsonSerializer;
  8. import com.fasterxml.jackson.databind.SerializerProvider;
  9. import java.io.IOException;
  10. /**
  11. * jackson处理以unicode方式编码中文
  12. */
  13. public class JacksonStringUnicodeSerializer extends JsonSerializer<String> {
  14. private final char[] HEX_CHARS = "0123456789ABCDEF".toCharArray();
  15. private final int[] ESCAPE_CODES = CharTypes.get7BitOutputEscapes();
  16. private void writeUnicodeEscape(JsonGenerator gen, char c) throws IOException {
  17. gen.writeRaw('\\');
  18. gen.writeRaw('u');
  19. gen.writeRaw(HEX_CHARS[(c >> 12) & 0xF]);
  20. gen.writeRaw(HEX_CHARS[(c >> 8) & 0xF]);
  21. gen.writeRaw(HEX_CHARS[(c >> 4) & 0xF]);
  22. gen.writeRaw(HEX_CHARS[c & 0xF]);
  23. }
  24. private void writeShortEscape(JsonGenerator gen, char c) throws IOException {
  25. gen.writeRaw('\\');
  26. gen.writeRaw(c);
  27. }
  28. @Override
  29. public void serialize(String str, JsonGenerator gen,
  30. SerializerProvider provider) throws IOException,
  31. JsonProcessingException {
  32. int status = ((JsonWriteContext) gen.getOutputContext()).writeValue();
  33. switch (status) {
  34. case JsonWriteContext.STATUS_OK_AFTER_COLON:
  35. gen.writeRaw(':');
  36. break;
  37. case JsonWriteContext.STATUS_OK_AFTER_COMMA:
  38. gen.writeRaw(',');
  39. break;
  40. case JsonWriteContext.STATUS_EXPECT_NAME:
  41. throw new JsonParseException("Can not write string value here", null);
  42. }
  43. gen.writeRaw('"');//写入JSON中字符串的开头引号
  44. for (char c : str.toCharArray()) {
  45. if (c >= 0x80){
  46. writeUnicodeEscape(gen, c); // 为所有非ASCII字符生成转义的unicode字符
  47. }else {
  48. // 为ASCII字符中前128个字符使用转义的unicode字符
  49. int code = (c < ESCAPE_CODES.length ? ESCAPE_CODES[c] : 0);
  50. if (code == 0){
  51. gen.writeRaw(c); // 此处不用转义
  52. }else if (code < 0){
  53. writeUnicodeEscape(gen, (char) (-code - 1)); // 通用转义字符
  54. }else {
  55. writeShortEscape(gen, (char) code); // 短转义字符 (\n \t ...)
  56. }
  57. }
  58. }
  59. gen.writeRaw('"');//写入JSON中字符串的结束引号
  60. }
  61. }