package com.mridul.automation.service.utilities;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public interface Jsonable {
Logger LOG = LoggerFactory.getLogger(Jsonable.class);
ObjectMapper MAPPER = new ObjectMapper().setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);
ObjectWriter WRITER = MAPPER.writerWithDefaultPrettyPrinter();
default String toJson() {
String json = null;
try {
json = WRITER.writeValueAsString(this);
} catch (final Exception e) {
LOG.info("Not able to serialize to json {}", e);
throw new RuntimeException(e);
}
return json;
}
default <T extends Jsonable> T fromJson(String json, Class<T> clazz) {
T t = null;
try {
t = MAPPER.readValue(json, clazz);
} catch (final Exception e) {
LOG.info("Exception parsing json {}", e);
throw new RuntimeException(e);
}
return t;
}
}
Comments
Post a Comment