Skip to content

Instantly share code, notes, and snippets.

@julianjupiter
Created August 13, 2023 15:04
Show Gist options
  • Save julianjupiter/671939cbaa7359345bc070cdb18cd2fa to your computer and use it in GitHub Desktop.
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
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()));
}
}
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