Skip to content

Instantly share code, notes, and snippets.

@dinomite
Created March 12, 2019 14:29
Show Gist options
  • Save dinomite/cf443f426e256b1404ec0b07e1413fbe to your computer and use it in GitHub Desktop.
Save dinomite/cf443f426e256b1404ec0b07e1413fbe to your computer and use it in GitHub Desktop.
/**
* Not thread safe due to asJson() indentation switching, but good enough for testing
*/
@NotThreadSafe
@SuppressFBWarnings(value = ["ST_WRITE_TO_STATIC_FROM_INSTANCE_METHOD"],
justification = "Findbugs doesn't understand Kotlin init")
object Json {
val objectMapper: ObjectMapper = ObjectMapper()
init {
objectMapper.registerModule(KotlinModule())
objectMapper.registerModule(JavaTimeModule())
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false)
objectMapper.configure(SerializationFeature.WRITE_ENUMS_USING_TO_STRING, false)
objectMapper.configure(SerializationFeature.INDENT_OUTPUT, true)
objectMapper.setConfig(objectMapper.serializationConfig.withView(Views.Public::class.java))
}
/**
* Converts the given object into a canonical JSON string.
*
* @param thing an object
* @return {@code thing} as a JSON string
* @throws IllegalArgumentException if there is an error encoding `object`
*/
fun asJson(thing: Any, indent: Boolean = true): String {
if (indent) {
return objectMapper.writeValueAsString(thing)
} else {
Json.objectMapper.configure(SerializationFeature.INDENT_OUTPUT, false)
val json = objectMapper.writeValueAsString(thing)
Json.objectMapper.configure(SerializationFeature.INDENT_OUTPUT, true)
return json
}
}
/**
* Converts the given JSON string into an object of the given type.
*
* @param json a JSON string
* @param klass the class of the type that `json` should be converted to
* @param <T> the type that {@code json} should be converted to
* @return {@code json} as an instance of `T`
* @throws IOException if there is an error reading `json` as an instance of `T`
*/
fun <T> fromJson(json: String, klass: Class<T>): T {
return objectMapper.readValue(json, klass)
}
/**
* Converts the given JSON string into an object of the given type.
*
* @param json a JSON string
* @param reference a reference of the type that `json` should be converted to
* @param <T> the type that {@code json} should be converted to
* @return {@code json} as an instance of {@code T}
* @throws IOException if there is an error reading `json` as an instance of `T`
*/
fun <T> fromJson(json: String, reference: TypeReference<T>): T {
return objectMapper.readValue<T>(json, reference)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment