|
1 | 1 | package com.exasol.common.json |
2 | 2 |
|
3 | | -import com.fasterxml.jackson.core.`type`.TypeReference |
| 3 | +import com.fasterxml.jackson.core.JsonParser |
| 4 | +import com.fasterxml.jackson.databind.MapperFeature |
| 5 | +import com.fasterxml.jackson.databind.SerializationFeature |
4 | 6 | import com.fasterxml.jackson.databind.json.{JsonMapper => BaseJsonMapper} |
5 | | -import com.fasterxml.jackson.module.scala.DefaultScalaModule |
| 7 | +import com.fasterxml.jackson.module.scala.ClassTagExtensions |
6 | 8 |
|
| 9 | +/** |
| 10 | + * JSON parsing helper object class. |
| 11 | + */ |
7 | 12 | object JsonMapper { |
8 | 13 |
|
9 | | - private[this] val mapper = BaseJsonMapper |
10 | | - .builder() |
11 | | - .addModule(DefaultScalaModule) |
12 | | - .build() |
| 14 | + private[this] class ScalaJsonMapper(jsonMapper: BaseJsonMapper) |
| 15 | + extends BaseJsonMapper(jsonMapper) |
| 16 | + with ClassTagExtensions |
13 | 17 |
|
| 18 | + private[this] val mapper = { |
| 19 | + val builder = BaseJsonMapper |
| 20 | + .builder() |
| 21 | + .findAndAddModules() |
| 22 | + .enable(MapperFeature.ACCEPT_CASE_INSENSITIVE_ENUMS) |
| 23 | + .enable(JsonParser.Feature.ALLOW_COMMENTS) |
| 24 | + .defaultMergeable(true) |
| 25 | + new ScalaJsonMapper(builder.build()) |
| 26 | + } |
| 27 | + |
| 28 | + /** |
| 29 | + * Parses given value type into a JSON string. |
| 30 | + * |
| 31 | + * For parsing into pretty indented JSON use {@link toPrettyJson}. |
| 32 | + * |
| 33 | + * @param value a provided value type |
| 34 | + * @return JSON string |
| 35 | + */ |
14 | 36 | def toJson[T](value: T): String = |
15 | 37 | mapper.writeValueAsString(value) |
16 | 38 |
|
| 39 | + /** |
| 40 | + * Parses given value into pretty JSON format. |
| 41 | + * |
| 42 | + * @param value a provided value type |
| 43 | + * @return pretty JSON string |
| 44 | + */ |
| 45 | + def toPrettyJson[T](value: T): String = |
| 46 | + mapper.writer(SerializationFeature.INDENT_OUTPUT).writeValueAsString(value) |
| 47 | + |
| 48 | + /** |
| 49 | + * Parses JSON string into a type. |
| 50 | + * |
| 51 | + * @param jsonString a JSON string |
| 52 | + * @return parsed value |
| 53 | + */ |
| 54 | + def fromJson[T: Manifest](jsonString: String): T = |
| 55 | + mapper.readValue[T](jsonString) |
| 56 | + |
| 57 | + /** |
| 58 | + * Parses JSON string into a type. |
| 59 | + * |
| 60 | + * @param jsonString a JSON string |
| 61 | + * @return parsed value |
| 62 | + */ |
| 63 | + @deprecated("Use fromJson method instead.", "0.3.1") |
17 | 64 | def parseJson[T: Manifest](jsonString: String): T = |
18 | | - mapper.readValue[T](jsonString, new TypeReference[T]() {}) |
| 65 | + fromJson(jsonString) |
19 | 66 |
|
20 | 67 | } |
0 commit comments