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 deserialize(String s, Class 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 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)); } }