]> git.basschouten.com Git - openhab-addons.git/blob
8907c7d4f85511dc644739b4ea79f002ee54c8f7
[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.livisismarthome.internal.client;
14
15 import java.util.Optional;
16
17 import org.eclipse.jdt.annotation.NonNullByDefault;
18 import org.eclipse.jdt.annotation.Nullable;
19
20 import com.google.gson.Gson;
21 import com.google.gson.GsonBuilder;
22 import com.google.gson.JsonSyntaxException;
23
24 /**
25  * The {@link GsonOptional} supports non-null-compatible methods to use gson.
26  *
27  * @author Sven Strohschein - Initial contribution
28  */
29 @NonNullByDefault
30 public class GsonOptional {
31
32     /**
33      * date format as used in json in API. Example: 2016-07-11T10:55:52.3863424Z
34      */
35     private static final String DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSSZ";
36
37     private final Gson gson = new GsonBuilder().setDateFormat(DATE_FORMAT).create();
38
39     public GsonOptional() {
40     }
41
42     public <T> Optional<T> fromJson(String json, Class<T> clazz) throws JsonSyntaxException {
43         return Optional.ofNullable(fromJsonNullable(json, clazz));
44     }
45
46     public <T> @Nullable T fromJsonNullable(String json, Class<T> clazz) throws JsonSyntaxException {
47         return gson.fromJson(json, clazz);
48     }
49
50     public String toJson(Object src) {
51         return gson.toJson(src);
52     }
53 }