Skip to content

Instantly share code, notes, and snippets.

@jclosure
Created July 4, 2016 07:20
Show Gist options
  • Select an option

  • Save jclosure/f10c47126e99bb2bc8c6df256b6bde16 to your computer and use it in GitHub Desktop.

Select an option

Save jclosure/f10c47126e99bb2bc8c6df256b6bde16 to your computer and use it in GitHub Desktop.
General purpose Json Serializer/Deserializer Util
// jackson 2 => compile 'com.fasterxml.jackson.core:jackson-core:2.6.3'
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.codehaus.jackson.map.DeserializationConfig;
import java.io.IOException;
/**
* Utility for serializing arbitrary classes to Json strings then
* back to their original objects. Provides default {@link ObjectMapper}
* behavior with public static methods, as well as versions accepting
* a user-configured {@link ObjectMapper}.
*/
public final class JsonSerializer {
private static final ObjectMapper defaultObjectMapper = new ObjectMapper();
public static void JsonSerializer() {
defaultObjectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
defaultObjectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
}
/**
* Serialize to JSON from a source object with
* the user-provided {@link ObjectMapper}.
*/
public static String serialize(Object source, ObjectMapper mapper) throws IOException {
return mapper.writeValueAsString(source);
}
/**
* Serialize to JSON from a source object using
* the default configuration of the {@link ObjectMapper}.
*/
public static String serialize(Object source) throws IOException {
return serialize(source, defaultObjectMapper);
}
/**
* Deserialize from JSON to a an object of type T using
* the user-provided {@link ObjectMapper}.
*/
public static <T> T deserialize(String source, ObjectMapper mapper, Class<T> cls) throws IOException {
return mapper.readValue(source, cls);
}
/**
* Deserialize from JSON to a an object of type T using
* the default configuration of the {@link ObjectMapper}.
*/
public static <T> T deserialize(String source, Class<T> cls) throws IOException {
return deserialize(source, defaultObjectMapper, cls);
}
private JsonSerializer() {
throw new UnsupportedOperationException("Cannot instantiate class '"+ getClass() +"'.");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment