提交 37f686cb authored 作者: Matrix's avatar Matrix

fix(base): 优化了转json部分

上级 1e6749c1
...@@ -187,7 +187,8 @@ public class MoveActuator implements Actuator { ...@@ -187,7 +187,8 @@ public class MoveActuator implements Actuator {
Map<String, List<Map<String, Object>>> res = resSet.get(); Map<String, List<Map<String, Object>>> res = resSet.get();
// 分类处理 + 结果集处理(如果不存在则put数据,如果存在则替换数据) // 分类处理 + 结果集处理(如果不存在则put数据,如果存在则替换数据)
LogQueueRuntime.addNewLog(this.getClass(), MOVE_ACTUATOR, String.format("正在执行动作 actionId = %d,动作类型 = %s,动作策略 = %s,动作参数 = %s", action.getId(), action, strategy, runtimeDetail)); LogQueueRuntime.addNewLog(this.getClass(), MOVE_ACTUATOR,
String.format("正在执行动作 actionId = %d,动作类型 = %s,动作策略 = %s,动作参数 = %s", action.getId(), action, strategy, runtimeDetail));
if (actionType == SQL_ACTION) { if (actionType == SQL_ACTION) {
List<Map<String, Object>> resultMap = sqlActionHandler(envId, projectId, runtimeDetail); List<Map<String, Object>> resultMap = sqlActionHandler(envId, projectId, runtimeDetail);
res.put(key, resultMap); res.put(key, resultMap);
......
package org.matrix.config;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.json.JsonReadFeature;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import java.text.SimpleDateFormat;
import java.util.TimeZone;
import static com.fasterxml.jackson.core.JsonParser.*;
/**
* JacksonConfig.
*
* @author Matrix <xhyrzldf@gmail.com>
* @since 2022/3/23 at 2:27 PM
* Suffering is the most powerful teacher of life.
*/
@Configuration
public class JacksonConfig {
@Bean("objectMapper")
@Primary
@ConditionalOnMissingBean(ObjectMapper.class)
public ObjectMapper getObjectMapper(Jackson2ObjectMapperBuilder builder) {
ObjectMapper mapper = builder.build();
// 日期格式
mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
//GMT+8
mapper.setTimeZone(TimeZone.getTimeZone("GMT+8"));
// Include.NON_NULL 属性为NULL 不序列化
//ALWAYS // 默认策略,任何情况都执行序列化
//NON_EMPTY // null、集合数组等没有内容、空字符串等,都不会被序列化
//NON_DEFAULT // 如果字段是默认值,就不会被序列化
//NON_ABSENT // null的不会序列化,但如果类型是AtomicReference,依然会被序列化
mapper.setSerializationInclusion(JsonInclude.Include.ALWAYS);
//允许字段名没有引号(可以进一步减小json体积):
mapper.configure(Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
//允许单引号:
mapper.configure(Feature.ALLOW_SINGLE_QUOTES, true);
// 允许出现特殊字符和转义符
//mapper.configure(Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true);这个已经过时。
mapper.configure(JsonReadFeature.ALLOW_UNESCAPED_CONTROL_CHARS.mappedFeature(), true);
//允许C和C++样式注释:
mapper.configure(Feature.ALLOW_COMMENTS, true);
//序列化结果格式化,美化输出
// mapper.enable(SerializationFeature.INDENT_OUTPUT);
//枚举输出成字符串
//WRITE_ENUMS_USING_INDEX:输出索引
mapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING);
//空对象不要抛出异常:
mapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
//Date、Calendar等序列化为时间格式的字符串(如果不执行以下设置,就会序列化成时间戳格式):
mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
//反序列化时,遇到未知属性不要抛出异常:
mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
//反序列化时,遇到忽略属性不要抛出异常:
mapper.disable(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES);
//反序列化时,空字符串对于的实例属性为null:
mapper.enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT);
return mapper;
}
}
package org.matrix.util;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.matrix.config.JacksonConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import java.io.IOException;
/**
* JsonUtil.
*
* @author Matrix <xhyrzldf@gmail.com>
* @since 2022/3/23 at 2:30 PM
* Suffering is the most powerful teacher of life.
*/
@Component
@ConditionalOnClass(JacksonConfig.class)
public class JsonUtil {
private static final Logger log = LoggerFactory.getLogger(JsonUtil.class);
public static ObjectMapper objectMapper;
public static ObjectMapper getObjectMapper() {
return objectMapper;
}
/**
* 静态变量注入时,@Autowired注解只能在方法,不能在参数
*/
@Autowired
public void setObjectMapper(ObjectMapper objectMapper) {
JsonUtil.objectMapper = objectMapper;
}
/**
* Object转json字符串
*/
public static <T> String toJson(T obj) {
try {
if (obj == null) {
return null;
} else if (obj instanceof String) {
return (String) obj;
} else {
return objectMapper.writeValueAsString(obj);
}
} catch (Exception e) {
log.error("Parse object to String error", e);
return null;
}
}
/**
* Object转json字符串并格式化美化
*/
public static <T> String toJsonPretty(T obj) {
try {
if (obj == null) {
return null;
} else if (obj instanceof String) {
return (String) obj;
} else {
return objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(obj);
}
} catch (Exception e) {
log.error("Parse object to String Pretty error", e);
return null;
}
}
/**
* json转object
*/
@SuppressWarnings("unchecked")
public static <T> T toBean(String json, Class<T> clazz) {
try {
if (StringUtils.hasText(json) || clazz == null) {
return null;
} else if (clazz.equals(String.class)) {
return (T) json;
} else {
return objectMapper.readValue(json, clazz);
}
} catch (IOException e) {
log.error("Parse String to bean error", e);
return null;
}
}
/**
* json转集合
*
* @param <T>
* @param json
* @param typeReference <li>new TypeReference<List<User>>() {}</li>
* @return
*/
@SuppressWarnings("unchecked")
public static <T> T toBean(String json, TypeReference<T> typeReference) {
try {
if (StringUtils.hasText(json) || typeReference == null) {
return null;
} else if (typeReference.getType().equals(String.class)) {
return (T) json;
} else {
return objectMapper.readValue(json, typeReference);
}
} catch (IOException e) {
log.error("Parse String to Bean error", e);
return null;
}
}
/**
* string转object 用于转为集合对象
*
* @param json Json字符串
* @param collectionClass 被转集合的类
* <p>List.class</p>
* @param elementClasses 被转集合中对象类型的类
* <p>User.class</p>
*/
public static <T> T toBean(String json, Class<?> collectionClass, Class<?>... elementClasses) {
try {
JavaType javaType = objectMapper.getTypeFactory().constructParametricType(collectionClass, elementClasses);
return objectMapper.readValue(json, javaType);
} catch (IOException e) {
log.error("Parse String to Bean error", e);
return null;
}
}
}
package org.matrix.autotest.controller;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.matrix.database.entity.Connect;
import org.matrix.util.JsonUtil;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Objects;
/**
* TestController.
*
* @author Matrix <xhyrzldf@gmail.com>
* @since 2022/3/22 at 4:56 PM
* Suffering is the most powerful teacher of life.
*/
@Api(tags = "一个单纯的测试接口,开发完之后会删除")
@RestController
@RequestMapping("/justTest")
public class JustTestController {
@GetMapping
@ApiOperation("普通的测试接口,开发完会删除")
public ResponseEntity<String> justForTest() {
//todo 开发完毕后会删除
return ResponseEntity.ok("这是一个单纯的测试接口");
}
@GetMapping("/jsonFormat")
@ApiOperation("测试静态注入的jackson的美化功能")
public ResponseEntity<String> jsonFormatTest() {
Connect connect = new Connect("测试", "测试", "测试", "测试", "测试", 2L);
String fastJsonString = JSON.toJSONString(connect);
String jacksonString1 = JsonUtil.toJson(connect);
String jacksonString2 = JsonUtil.toJsonPretty(connect);
System.out.printf("fastJsonString = %s %n jacksonString1 = %s %n jacksonString2 %s %n %n",
fastJsonString, jacksonString1, jacksonString2);
return ResponseEntity.ok(Objects.requireNonNull(fastJsonString));
}
}
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论