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

Kai Reinhard
04.58.2019 6ff74e6e78e27fbcb751dcf20c9e61dafb78caed
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
package de.micromata.borgbutler.json;
 
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
 
import java.io.IOException;
import java.io.StringWriter;
 
public class JsonUtils {
    private static Logger log = LoggerFactory.getLogger(JsonUtils.class);
 
    public static String toJson(Object obj) {
        return toJson(obj, false);
    }
 
    /**
     * @param obj
     * @param prettyPrinter If true, the json output will be pretty printed (human readable with new lines and indenting).
     * @return
     */
    public static String toJson(Object obj, boolean prettyPrinter) {
        if (obj == null) {
            return "";
        }
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        try {
            if (prettyPrinter) {
                return objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(obj);
            } else {
                StringWriter writer = new StringWriter();
                objectMapper.writeValue(writer, obj);
                return writer.toString();
            }
        } catch (IOException ex) {
            log.error(ex.getMessage(), ex);
            return "";
        }
    }
 
    public static <T> T fromJson(Class<T> clazz, String json) {
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        try {
            return objectMapper.readValue(json, clazz);
        } catch (IOException ex) {
            log.error(ex.getMessage(), ex);
            return null;
        }
    }
 
    public static <T> T fromJson(final TypeReference<T> type, final String json) {
        try {
            T data = new ObjectMapper().readValue(json, type);
            return data;
        } catch (Exception ex) {
            log.error("Json: '" + json + "': " + ex.getMessage(), ex);
        }
        return null;
    }
}