发布于2026-07-11 阅读(0)
扫一扫,手机访问
工作里头偶然碰上了需要把实体类和字符串互相倒腾一下的需求,顺手把这过程记下来,没准儿后来人能少走两步弯路。

假设有一个满减类型的配置实体,里面定义了“满几件”和“打几折”这两个关键字段。这类实体在业务里挺常见,比如促销活动规则、商品属性配置等等。
@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这把瑞士军刀。我们用Jackson来干这个活,代码不复杂,但功能齐全:支持对象转字符串、字符串转对象、字符串转List、字符串转Map——基本覆盖了日常开发中的常见姿势。
package com.kaying.star.system.common.util.json;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.Ja vaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import ja va.util.List;
import ja va.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 json2Bean(String jsonData, Class beanType) {
try {
T result = objectMapper.readValue(jsonData, beanType);
return result;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public List json2List(String jsonData, Class beanType) {
Ja vaType ja vaType = objectMapper.getTypeFactory().constructParametricType(List.class, beanType);
try {
List resultList = objectMapper.readValue(jsonData, ja vaType);
return resultList;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public Map json2Map(String jsonData, Class keyType, Class valueType) {
Ja vaType ja vaType = objectMapper.getTypeFactory().constructMapType(Map.class, keyType, valueType);
try {
Map resultMap = objectMapper.readValue(jsonData, ja vaType);
return resultMap;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
调用工具类一行搞定:
String disConfig = jsonUtils.bean2Json(discountTypeConfig)
反过来也是同样的套路:
//通过实体类转成的string String disConfig = jsonUtils.bean2Json(discountTypeConfig) //通过工具类将string转换成实体类 DiscountTypeConfig discountTypeConfig = jsonUtils.json2Bean(disConfig , DiscountTypeConfig.class)
这种做法特别适合各种动态配置场景——比如活动规则、用户个性化设置、产品参数模板等等。一句话总结:实体类转成字符串,存进数据库;从库中取出字符串,再还原成实体类,完美闭环。
这其实不算什么高深技术,但胜在实用。希望这段经验能帮到正在纠结这类问题的朋友,省去自己造轮子的时间。
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
正版软件
正版软件
正版软件
正版软件
正版软件
1
2
3
7
8