mirror of https://github.com/micromata/borgbackup-butler.git

Kai Reinhard
17.59.2021 c6e77f6fa462e292db5f693a33e7c483b5a6e19e
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
package de.micromata.borgbutler.json
 
import com.fasterxml.jackson.annotation.JsonInclude
import com.fasterxml.jackson.core.io.JsonStringEncoder
import com.fasterxml.jackson.core.type.TypeReference
import com.fasterxml.jackson.databind.DeserializationFeature
import com.fasterxml.jackson.databind.ObjectMapper
import mu.KotlinLogging
import org.slf4j.LoggerFactory
import java.io.IOException
import java.io.StringWriter
 
private val log = KotlinLogging.logger {}
 
object JsonUtils {
    /**
     * @param obj
     * @param prettyPrinter If true, the json output will be pretty printed (human readable with new lines and indenting).
     * @return
     */
    @JvmOverloads
    @JvmStatic
    fun toJson(obj: Any?, prettyPrinter: Boolean? = false): String {
        if (obj == null) {
            return ""
        }
        val objectMapper = ObjectMapper()
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL)
        return try {
            if (prettyPrinter == true) {
                objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(obj)
            } else {
                val writer = StringWriter()
                objectMapper.writeValue(writer, obj)
                writer.toString()
            }
        } catch (ex: IOException) {
            log.error(ex.message, ex)
            ""
        }
    }
 
    @JvmStatic
    fun toJson(str: String?): String {
        return if (str == null) "" else String(JsonStringEncoder.getInstance().quoteAsString(str))
    }
 
    @JvmStatic
    fun <T> fromJson(clazz: Class<T>?, json: String?): T? {
        val objectMapper = ObjectMapper()
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
        return try {
            objectMapper.readValue(json, clazz)
        } catch (ex: IOException) {
            log.error(ex.message, ex)
            null
        }
    }
 
    @JvmStatic
    fun <T> fromJson(type: TypeReference<T>?, json: String): T? {
        try {
            return ObjectMapper().readValue(json, type)
        } catch (ex: Exception) {
            log.error("Json: '" + json + "': " + ex.message, ex)
        }
        return null
    }
}