赞
踩
例子:
有一个实体类StudentInfo
放在一个List中,为List infoList;
现在需要把这个infoList 以字符串的形式存起来,示例如下:
@Data
public class StudentInfo{
/**
* 学生姓名
*/
private String name;
/**
* 学生年龄
*/
private String age;
}
下面示例代码为将入参infoList转为JSON字符串输出
public class StudentInfoServiceImpl implements StudentInfoService {
@Override
public String listTransToString(List<StudentInfo> infoList) {
ObjectMapper objectMapper = new ObjectMapper();
try {
String studentInfoJsonString = objectMapper.writeValueAsString(infoList);
return studentInfoJsonString;
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return null;
}
}
下面示例代码为将JSON字符串转为List
@Override
public List<StudentInfo> stringTransToList(String studentInfoJsonString) {
// 创建 ObjectMapper 对象
ObjectMapper objectMapper = new ObjectMapper();
try {
List<StudentInfo> infoList = objectMapper.readValue(chatContent, new TypeReference<>() {
});
return infoList;
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return null;
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。