在工作中偶然遇到需要将实体类与String互转的情况,简单记录一下
准备一个实体类
@ApiModel(description = "满减类型配置")
@Data
public class DiscountTypeConfig {
/**
* 满几件
*/
@ApiModelProperty(name = "full_goods_num", value = "满几件", required = true)
@NotNull(message = "满几件不能为空")
@Range(min = 1, message = "满几件必须大于0")
private Integer fullGoodsNum;
/**
* 打几折(百分比)
*/
@ApiModelProperty(name = "percentage_discount", value = "打几折(百分比)", required = true)
@NotNull(message = "打几折(百分比)不能为空")
@Range(min = 1, max = 99, message = "打几折(百分比)必须大于0小于100")
private Integer percentageDiscount;
准备json工具类
package com.kaying.star.system.common.util.json;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.Map;
/**
* json工具类
*
*/
@Component
public class JsonUtils {
@Autowired
private ObjectMapper objectMapper;
public String bean2Json(Object data) {
try {
String result = objectMapper.writeValueAsString(data);
return result;
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return null;
}
public <T> T json2Bean(String jsonData, Class<T> beanType) {
try {
T result = objectMapper.readValue(jsonData, beanType);
return result;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public <T> List<T> json2List(String jsonData, Class<T> beanType) {
JavaType javaType = objectMapper.getTypeFactory().constructParametricType(List.class, beanType);
try {
List<T> resultList = objectMapper.readValue(jsonData, javaType);
return resultList;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public <K, V> Map<K, V> json2Map(String jsonData, Class<K> keyType, Class<V> valueType) {
JavaType javaType = objectMapper.getTypeFactory().constructMapType(Map.class, keyType, valueType);
try {
Map<K, V> resultMap = objectMapper.readValue(jsonData, javaType);
return resultMap;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
转成string之后可以保存至数据库
String disConfig = jsonUtils.bean2Json(discountTypeConfig)
从数据库中取出String字段,将String转成实体类
//通过实体类转成的string
String disConfig = jsonUtils.bean2Json(discountTypeConfig)
//通过工具类将string转换成实体类
DiscountTypeConfig discountTypeConfig = jsonUtils.json2Bean(disConfig , DiscountTypeConfig.class)
适用于各种不同的配置等使用场景,将实体类转成string存入数据库,将string取出转成实体类!