需要使用 Jackson JSON处理 jar包,主要使用 ObjectMapper
object 转成 json
public static String objectToJson(Object value) {
try {
return new ObjectMapper().writeValueAsString(value);
} catch (JsonProcessingException ex) {
throw new IllegalArgumentException("Cannot parse object to JSON", ex);
}
}
json 转成 object
public static T jsonToObject(String json, Class clazz) {
try {
return new ObjectMapper().readValue(json, clazz);
} catch (IOException ex) {
throw new IllegalArgumentException(
"Cannot parse the specified JSON string into " + clazz, ex);
}
}