添加工具类,在工具类中添加静态方法。
private static final ObjectMapper MAPPER = new ObjectMapper();
//2.封装数据
public static String toJSON(Object object) {
if (object == null) {
throw new RuntimeException("传入对象不能为空");
}
try {
String s = MAPPER.writeValueAsString(object);
return s;
} catch (JsonProcessingException e) {
e.printStackTrace();
throw new RuntimeException(e.getMessage());
}
}
//3.将JSON串转换为对象
public static T toObject(String json, Class target) {
if (json == null || "".equals(json) || target == null) {
throw new RuntimeException("参数不能为空");
}
try {
T s = MAPPER.readValue(json, target);
return s;
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException(e.getMessage());
}
}
二、json与数组的相互转化
1、json转数组
调用方法JSONArray.parseArray(String json,Object T),即可将json数据转为T类的数组
2、数组转json
可直接调用上述工具类中toJSON(Object object)方法将数组类型换为String类型



