例子:
有一个实体类StudentInfo
放在一个List中,为List infoList;
现在需要把这个infoList 以字符串的形式存起来,示例如下:
@Datapublic 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; }
来源地址:https://blog.csdn.net/Mico_Cmx/article/details/131571926