Is there a way I can make the static method toObject
generic by passing the T class and return type T?
public class JsonUtil {
private JsonUtil() {
}
public static Object toObject(String jsonString, Class clazz, boolean unwrapRootValue) throws TechnicalException {
ObjectMapper mapper = new ObjectMapper();
mapper.writerWithDefaultPrettyPrinter();
if (unwrapRootValue) mapper.enable(DeserializationFeature.UNWRAP_ROOT_VALUE);
try {
return mapper.readValue(jsonString, clazz);
} catch (IOException e) {
throw new TechnicalException("Exception while converting JSON to Object", e);
}
}
}
Sure. Just specify a generic type parameter on the method itself, and use it for both the return type and the clazz
parameter:
public static <T> T toObject(String jsonString, Class<T> clazz,
boolean unwrapRootValue) throws TechnicalException {
/* ... */
}
public class JsonUtil {
private JsonUtil() {
}
public static <T> T toObject(String jsonString, Class<? extends T> clazz, boolean unwrapRootValue) throws TechnicalException {
ObjectMapper mapper = new ObjectMapper();
mapper.writerWithDefaultPrettyPrinter();
if (unwrapRootValue) mapper.enable(DeserializationFeature.UNWRAP_ROOT_VALUE);
try {
return mapper.readValue(jsonString, clazz);
} catch (IOException e) {
throw new TechnicalException("Exception while converting JSON to Object", e);
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.