2019-10-04 15:55:45 -04:00
|
|
|
package com.chameleonvision.util;
|
2019-09-19 14:07:42 -04:00
|
|
|
|
2019-11-12 19:28:46 +02:00
|
|
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
|
|
|
|
import com.fasterxml.jackson.databind.json.JsonMapper;
|
|
|
|
|
import com.fasterxml.jackson.databind.jsontype.BasicPolymorphicTypeValidator;
|
|
|
|
|
import com.fasterxml.jackson.databind.jsontype.PolymorphicTypeValidator;
|
|
|
|
|
import java.io.File;
|
2019-09-19 14:07:42 -04:00
|
|
|
import java.io.IOException;
|
|
|
|
|
import java.nio.file.Files;
|
|
|
|
|
import java.nio.file.Path;
|
|
|
|
|
|
2019-11-26 17:57:51 -05:00
|
|
|
public class JacksonHelper {
|
|
|
|
|
private JacksonHelper() {} // no construction, utility class
|
2019-09-19 14:07:42 -04:00
|
|
|
|
2019-11-27 19:39:08 -05:00
|
|
|
public static <T> void serializer(Path path, T object) throws IOException {
|
|
|
|
|
PolymorphicTypeValidator ptv = BasicPolymorphicTypeValidator.builder().allowIfBaseType(object.getClass()).build();
|
2019-11-12 19:28:46 +02:00
|
|
|
ObjectMapper objectMapper = JsonMapper.builder().activateDefaultTyping(ptv, ObjectMapper.DefaultTyping.JAVA_LANG_OBJECT).build();
|
2019-11-21 05:32:19 -05:00
|
|
|
objectMapper.writerWithDefaultPrettyPrinter().writeValue(new File(path.toString()), object);
|
2019-11-12 19:28:46 +02:00
|
|
|
}
|
|
|
|
|
|
2019-11-26 17:57:51 -05:00
|
|
|
public static <T> T deserializer(Path path, Class<T> ref) throws IOException {
|
2019-11-21 05:32:19 -05:00
|
|
|
PolymorphicTypeValidator ptv = BasicPolymorphicTypeValidator.builder().allowIfBaseType(ref).build();
|
2019-11-27 19:39:08 -05:00
|
|
|
ObjectMapper objectMapper = JsonMapper.builder().activateDefaultTyping(ptv, ObjectMapper.DefaultTyping.JAVA_LANG_OBJECT).build();
|
2019-11-21 05:32:19 -05:00
|
|
|
File jsonFile = new File(path.toString());
|
|
|
|
|
if (jsonFile.exists() && jsonFile.length() > 0) {
|
2019-11-26 17:57:51 -05:00
|
|
|
return objectMapper.readValue(jsonFile, ref);
|
2019-11-21 05:32:19 -05:00
|
|
|
}
|
|
|
|
|
return null;
|
2019-11-12 19:28:46 +02:00
|
|
|
}
|
2019-09-19 14:07:42 -04:00
|
|
|
}
|