Last active
September 4, 2021 00:42
-
-
Save edjeordjian/08c215a2b3453f6b5054902a72a9d338 to your computer and use it in GitHub Desktop.
Map a file (for example, a JSON) into an object with a few lines of code in Spring Boot.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import com.fasterxml.jackson.core.type.TypeReference; | |
import com.fasterxml.jackson.databind.*; | |
import org.springframework.util.ResourceUtils; | |
import java.io.IOException; | |
public class FileLoaderExample { | |
public static <DTO> DTO getDto(String path, Class<DTO> clazz) { | |
DTO dto = null; | |
try { | |
dto = new ObjectMapper().readValue(ResourceUtils.getFile(path), | |
clazz); | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} | |
return dto; | |
} | |
/* | |
// Inefficient way to use getDTO function to get the json content | |
// in String format. | |
public static final ObjectWriter objectMapper = new ObjectMapper() | |
.configure(SerializationFeature.WRAP_ROOT_VALUE, false) | |
.writer().withDefaultPrettyPrinter(); | |
public static String jsonToString(String jsonRoute, Class clazz) { | |
try { | |
return objectMapper.writeValueAsString( | |
getDto(jsonRoute, clazz)); | |
} catch (JsonProcessingException e) { | |
return "invalid json"; | |
} | |
} | |
*/ | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment