实体类的json/对象转换工具类
以下以QuestionVo为例,对其中的tags和judgeConfig字段进行json和对象的转换.
场景:在与前端交互中,tags和judgeConfig需要存储多个数据或字段,所以在QuestionVo中分别为List和JudgeConfig类型。而在数据库的存储中,tags标签有多个数据,为避免库中数据的冗余,先将其转成json字符串在存入数据库;JudgeConfig类中的字段在开发过程中不确定因素较多,为方便对字段进行扩展和修改,将其转成json字符串再存入数据库。
QuestionVo实体类
java
/**
* 题目封装类
* @TableName question
*/
@Data
public class QuestionVO implements Serializable {
private Long id;
private String title;
private String content;
private List<String> tags;
private Integer submitNum;
private Integer acceptedNum;
private JudgeConfig judgeConfig;
private Integer thumbNum;
private Integer favourNum;
private Long userId;
private Date createTime;
private Date updateTime;
private UserVO userVO;
/**
* 包装类转对象
*
* @param questionVO
* @return
*/
public static Question voToObj(QuestionVO questionVO) {
if (questionVO == null) {
return null;
}
Question question = new Question();
BeanUtils.copyProperties(questionVO, question);
List<String> tagList = questionVO.getTags();
if (tagList != null) {
question.setTags(JSONUtil.toJsonStr(tagList));
}
JudgeConfig voJudgeConfig = questionVO.getJudgeConfig();
if (voJudgeConfig != null) {
question.setJudgeConfig(JSONUtil.toJsonStr(voJudgeConfig));
}
return question;
}
/**
* 对象转包装类
*
* @param question
* @return
*/
public static QuestionVO objToVo(Question question) {
if (question == null) {
return null;
}
QuestionVO questionVO = new QuestionVO();
BeanUtils.copyProperties(question, questionVO);
List<String> tagList = JSONUtil.toList(question.getTags(), String.class);
questionVO.setTags(tagList);
String judgeConfigStr = question.getJudgeConfig();
questionVO.setJudgeConfig(JSONUtil.toBean(judgeConfigStr, JudgeConfig.class));
return questionVO;
}
private static final long serialVersionUID = 1L;
}
Question实体类
java
/**
* 题目
* @TableName question
*/
@TableName(value ="question")
@Data
public class Question implements Serializable {
@TableId(type = IdType.ASSIGN_ID)
private Long id;
private String title;
private String content;
private String tags;
private String answer;
private Integer submitNum;
private Integer acceptedNum;
private String judgeCase;
private String judgeConfig;
private Integer thumbNum;
private Integer favourNum;
private Long userId;
private Date createTime;
private Date updateTime;
@TableLogic
private Integer isDelete;
@TableField(exist = false)
private static final long serialVersionUID = 1L;
}
JudgeConfig实体类
java
/**
* 题目配置
*/
@Data
public class JudgeConfig {
private Long timeLimit;
private Long memoryLimit;
private Long stackLimit;
}