实体类与String相互转换

时间:2025-01-18 17:38:53

在工作中偶然遇到需要将实体类与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 ;

import ;
import ;
import ;
import ;
import ;

import ;
import ;

/**
 * json工具类
 *
 */
@Component
public class JsonUtils {
    @Autowired
    private ObjectMapper objectMapper;

    public String bean2Json(Object data) {
        try {
            String result = (data);
            return result;
        } catch (JsonProcessingException e) {
            ();
        }
        return null;
    }

    public <T> T json2Bean(String jsonData, Class<T> beanType) {
        try {
            T result = (jsonData, beanType);
            return result;
        } catch (Exception e) {
            ();
        }
        return null;
    }

    public <T> List<T> json2List(String jsonData, Class<T> beanType) {
        JavaType javaType = ().constructParametricType(, beanType);
        try {
            List<T> resultList = (jsonData, javaType);
            return resultList;
        } catch (Exception e) {
            ();
        }
        return null;
    }

    public <K, V> Map<K, V> json2Map(String jsonData, Class<K> keyType, Class<V> valueType) {
        JavaType javaType = ().constructMapType(, keyType, valueType);
        try {
            Map<K, V> resultMap = (jsonData, javaType);
            return resultMap;
        } catch (Exception e) {
            ();
        }
        return null;
    }
}

转成string之后可以保存至数据库

String disConfig = jsonUtils.bean2Json(discountTypeConfig)

从数据库中取出String字段,将String转成实体类

//通过实体类转成的string 
String disConfig = jsonUtils.bean2Json(discountTypeConfig)

//通过工具类将string转换成实体类
DiscountTypeConfig discountTypeConfig = jsonUtils.json2Bean(disConfig , )

适用于各种不同的配置等使用场景,将实体类转成string存入数据库,将string取出转成实体类!