2 * Copyright (c) 2010-2023 Contributors to the openHAB project
4 * See the NOTICE file(s) distributed with this work for additional
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
11 * SPDX-License-Identifier: EPL-2.0
13 package org.openhab.binding.icloud.internal.utilities;
15 import java.lang.reflect.Type;
18 import org.eclipse.jdt.annotation.NonNull;
19 import org.eclipse.jdt.annotation.NonNullByDefault;
20 import org.eclipse.jdt.annotation.Nullable;
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;
28 * Some helper method to ease and centralize use of GSON.
30 * @author Patrik Gfeller - Initial Contribution
31 * @author Simon Spielmann - Rename and generalization
35 public class JsonUtils {
36 private static final Gson GSON = new GsonBuilder().create();
38 private static final Type STRING_OBJ_MAP_TYPE = new TypeToken<Map<String, Object>>() {
42 * Parse JSON to {@link Map}
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.
48 public static @Nullable Map<String, Object> toMap(@Nullable String json) throws JsonSyntaxException {
49 return GSON.fromJson(json, STRING_OBJ_MAP_TYPE);
53 * Converts to JSON with {@link Gson}{@link #toJson(Object)}.
55 * @param data Data to convert.
56 * @return JSON representation of data.
58 public static @Nullable String toJson(@Nullable Object data) {
59 return GSON.toJson(data);
63 * Defaults to {@link Gson#fromJson(String, Class)}.
65 * @param data Data to parse.
66 * @param classOfT Destination type
67 * @param <T> Destination type param
68 * @return Given type or {@code null}.
70 * @see Gson#fromJson(String, Class)
72 public static <@Nullable T> T fromJson(String data, Class<@NonNull T> classOfT) {
73 return GSON.fromJson(data, classOfT);