Posts

Showing posts from February, 2018

Jsonable interface for providing json read write properties to an object

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> cl