]> git.basschouten.com Git - openhab-addons.git/blob
5c65c9a2a3d114822680ce3fdaeea90c22713b44
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2022 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;
38
39     public GsonOptional() {
40         gson = new GsonBuilder().setDateFormat(DATE_FORMAT).create();
41     }
42
43     public <T> Optional<T> fromJson(String json, Class<T> clazz) throws JsonSyntaxException {
44         return Optional.ofNullable(fromJsonNullable(json, clazz));
45     }
46
47     public <T> @Nullable T fromJsonNullable(String json, Class<T> clazz) throws JsonSyntaxException {
48         return gson.fromJson(json, clazz);
49     }
50
51     public String toJson(Object src) {
52         return gson.toJson(src);
53     }
54 }