]> git.basschouten.com Git - openhab-addons.git/blob
98603720177b5b057a8ca35ca1ef718d58581c24
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2023 Contributors to the openHAB project
3  *
4  * See the NOTICE file(s) distributed with this work for additional
5  * information.
6  *
7  * This program and the accompanying materials are made available under the
8  * terms of the Eclipse Public License 2.0 which is available at
9  * http://www.eclipse.org/legal/epl-2.0
10  *
11  * SPDX-License-Identifier: EPL-2.0
12  */
13 package org.openhab.binding.icloud.internal.utilities;
14
15 import java.lang.reflect.Type;
16 import java.util.Map;
17
18 import org.eclipse.jdt.annotation.NonNull;
19 import org.eclipse.jdt.annotation.NonNullByDefault;
20 import org.eclipse.jdt.annotation.Nullable;
21
22 import com.google.gson.Gson;
23 import com.google.gson.GsonBuilder;
24 import com.google.gson.JsonSyntaxException;
25 import com.google.gson.reflect.TypeToken;
26
27 /**
28  * Some helper method to ease and centralize use of GSON.
29  *
30  * @author Patrik Gfeller - Initial Contribution
31  * @author Simon Spielmann - Rename and generalization
32  *
33  */
34 @NonNullByDefault
35 public class JsonUtils {
36     private static final Gson GSON = new GsonBuilder().create();
37
38     private static final Type STRING_OBJ_MAP_TYPE = new TypeToken<Map<String, Object>>() {
39     }.getType();
40
41     /**
42      * Parse JSON to {@link Map}
43      *
44      * @param json JSON String or {@code null}.
45      * @return Parsed data or {@code null}
46      * @throws JsonSyntaxException If there is a JSON syntax error.
47      */
48     public static @Nullable Map<String, Object> toMap(@Nullable String json) throws JsonSyntaxException {
49         return GSON.fromJson(json, STRING_OBJ_MAP_TYPE);
50     }
51
52     /**
53      * Converts to JSON with {@link Gson}{@link #toJson(Object)}.
54      *
55      * @param data Data to convert.
56      * @return JSON representation of data.
57      */
58     public static @Nullable String toJson(@Nullable Object data) {
59         return GSON.toJson(data);
60     }
61
62     /**
63      * Defaults to {@link Gson#fromJson(String, Class)}.
64      *
65      * @param data Data to parse.
66      * @param classOfT Destination type
67      * @param <T> Destination type param
68      * @return Given type or {@code null}.
69      *
70      * @see Gson#fromJson(String, Class)
71      */
72     public static <@Nullable T> T fromJson(String data, Class<@NonNull T> classOfT) {
73         return GSON.fromJson(data, classOfT);
74     }
75 }