开发小技巧(一)

小案例

 public static void main(String[] args) throws Exception {
        String string="@#$%^&*()><??~@~!@#$%^&\"*()<>?:!@";
        String templateContent="[{\"name\":\""+string+"\"}]";
        ObjectMapper objectMapper = new ObjectMapper();
        List<Map<String, Object>> list1 = objectMapper.readValue(templateContent, new TypeReference<List<Map<String, Object>>>() {});
        System.out.println(list1);
    }

这个是一个正常的json转化。执行如下:
image.png

没错,他报错了。

平时我们遇到特殊字符,乱码我们很难处理。

我们可以先对特殊字符采用base64,转化后,在编码回来就行。

正确处理:

 public static void main(String[] args) throws Exception {
        final BASE64Encoder encoder = new BASE64Encoder();
        final BASE64Decoder decoder = new BASE64Decoder();
        String string="@#$%^&*()><??~@~!@#$%^&\"*()<>?:!@";
        //先对特殊字符串base64
        String encode = encoder.encode(string.getBytes());
        String templateContent="[{\"name\":\""+encode+"\"}]";
        ObjectMapper objectMapper = new ObjectMapper();
        List<Map<String, Object>> list1 = objectMapper.readValue(templateContent, new com.fasterxml.jackson.core.type.TypeReference<List<Map<String, Object>>>() {});
        for (Map<String, Object> map:list1){
            String string1 = String.valueOf(map.get("name"));
            if (isBase64(string1)){
                String string2 = new String(decoder.decodeBuffer(string1));
                map.put("name",string2);
            }
        }
        System.out.println(list1);
    }

  private static boolean isBase64(String str) {
        String base64Pattern = "^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{4}|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)$";
        return Pattern.matches(base64Pattern, str);
    }


image.png

评论

伏尔泰说:“使人疲惫的不是远方的高山,而是鞋子里的一粒沙。”
Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×