nouritsu/src/main/java/nouritsu/Serde.java

25 lines
917 B
Java

package nouritsu;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.vavr.control.Try;
import io.vavr.jackson.datatype.VavrModule;
/**
* *Ser*ialize and *de*serialize. Name stolen from the Rust framework.
*/
public class Serde {
private static final ObjectMapper MAPPER = new ObjectMapper().registerModule(new VavrModule());
public static <T> T deserialize(String s, Class<T> clazz) {
return Try.of(() -> MAPPER.readValue(s, clazz))
// I don’t see a case where this can actually happen
.getOrElseThrow((e) -> new IllegalArgumentException("Could not deserialize %s as %s".formatted(s, clazz), e));
}
public static <T> String serialize(T obj) {
return Try.of(() -> MAPPER.writeValueAsString(obj))
// unreachable, but checked exceptions force me to do this
.getOrElseThrow((e) -> new IllegalArgumentException("Could not serialize " + obj.toString(), e));
}
}