Gaofangye

Gaofangye

Jackson Common Operations for JSON

Public Section#

private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();

public static ObjectMapper getObjectMapper() {
    return OBJECT_MAPPER;
}

Convert JSON to a class with generics#

/**
 * Convert JSON to a class with generics
 *
 * @param json     JSON
 * @param javaType Generic class
 * @param <T>      Generics
 * @return Generic entity class
 */
public static <T> T toBean(String json, JavaType javaType) {
    try {
        return OBJECT_MAPPER.readValue(json, javaType);
    } catch (Exception e) {
        log.error("Failed to convert JSON to a Class object with generics using Jackson, reason for failure: {}", e.getMessage(), e);
        throw new RuntimeException(e);
    }
}

Example:

JavaType javaType = getObjectMapper().getTypeFactory().constructParametricType(ReqEntityPublic.class, UserDTO.class);
ReqEntityPublic<UserDTO> reqEntityPublic = toBean(jsonStr, javaType);
Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.