- package com.example.demo;
-
- import com.alibaba.druid.util.StringUtils;
- import com.alibaba.fastjson2.JSONObject;
- import com.alibaba.fastjson2.TypeReference;
- import com.fasterxml.jackson.core.JsonProcessingException;
- import com.fasterxml.jackson.databind.ObjectMapper;
-
- public final class SafeUtil {
- // <替换符1 usage
- private static final String LT = "<";
- private static final String LT_REPLACE = "<";
- // >替换符1 usage
- private static final String GT = ">";
- private static final String GT_REPLACE = ">";
-
-
- public static <T> T processScript(Object jsonString, TypeReference<T> type) {
- if (jsonString == null || type == null){
- return null;
- }
- String input = null;
- try {
- input = new ObjectMapper().writeValueAsString(jsonString);
- } catch (JsonProcessingException e) {
- throw new RuntimeException(e);
- }
- if (StringUtils.isEmpty(input)) {
- return null;
- }
- return JSONObject.parseObject(input.replaceAll(LT, LT_REPLACE).replaceAll(GT, GT_REPLACE), type);
- }
- }
使用
- @RequestMapping("/test")
- public Result<String> test(){
- return userService.get();
- }
-
- 新
- @RequestMapping("/test")
- public Result<String> test(){
- return SafeUtil.processScript(userService.get(), TypeReference<Result<String>>);
- }