Created
August 13, 2023 15:04
-
-
Save julianjupiter/671939cbaa7359345bc070cdb18cd2fa to your computer and use it in GitHub Desktop.
Read XML file from resources directory and deserialize it into POJO using Jackson
This file contains 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
public class App { | |
public static void main(String[] args) { | |
record User(String id, String name) {} | |
var reader = XmlResourceReader.create(User.class); | |
// src/main/resources/files/user.xml | |
reader.read("files/user.xml") | |
.ifPresent(user -> System.out.pritnln(user.id() + " " + user.name())); | |
} | |
} |
This file contains 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.dataformat.xml.XmlMapper; | |
import java.io.IOException; | |
import java.util.Optional; | |
public final class XmlResourceReader<T> { | |
private final Class<T> model; | |
private XmlResourceReader(Class<T> model) { | |
this.model = model; | |
} | |
public static <T> XmlResourceReader<T> create(Class<T> model) { | |
return new XmlResourceReader<>(model); | |
} | |
public Optional<T> read(String fileName) { | |
var classLoader = this.getClass().getClassLoader(); | |
var inputStream = classLoader.getResourceAsStream(fileName); | |
try { | |
return Optional.of(new XmlMapper().readValue(inputStream, this.model)); | |
} catch (IOException e) { | |
e.getStackTrace(); | |
return Optional.empty(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment