]> git.basschouten.com Git - openhab-addons.git/blob
b4ee02099aca679f9f9eaba6c805b88b86ed1e3f
[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.io.hueemulation.internal.dto.response;
14
15 import java.lang.reflect.Type;
16 import java.util.List;
17
18 import com.google.gson.Gson;
19 import com.google.gson.JsonElement;
20 import com.google.gson.JsonObject;
21 import com.google.gson.JsonSerializationContext;
22 import com.google.gson.JsonSerializer;
23
24 /**
25  * This response object is a bit complicated. The response is required to look like this:
26  *
27  * <pre>
28  * {
29  *   "success":{
30  *   "/1d49eeed-1fa7-434a-8e6c-70bb2cdc3e8f/lights/1/state/on": true
31  *   }
32  * }
33  * </pre>
34  *
35  * This object describes the right hand side of "success". The json key itself is the uri path
36  * and the value is either a boolean, number or string.
37  *
38  * This is done with a custom serializer that creates the proper {@link JsonObject}.
39  *
40  * @author David Graeff - Initial contribution
41  */
42 public class HueSuccessResponseStateChanged extends HueSuccessResponse {
43     private transient Object value;
44     private transient String relURI;
45
46     public HueSuccessResponseStateChanged(String relURI, Object value) {
47         this.relURI = relURI;
48         this.value = value;
49     }
50
51     public static class Serializer implements JsonSerializer<HueSuccessResponseStateChanged> {
52         @Override
53         public JsonElement serialize(HueSuccessResponseStateChanged product, Type type, JsonSerializationContext jsc) {
54             JsonObject jObj = new JsonObject();
55             if (product.value instanceof Float) {
56                 jObj.addProperty(product.relURI, (Float) product.value);
57             }
58             if (product.value instanceof Double) {
59                 jObj.addProperty(product.relURI, (Double) product.value);
60             }
61             if (product.value instanceof Integer) {
62                 jObj.addProperty(product.relURI, (Integer) product.value);
63             }
64             if (product.value instanceof Boolean) {
65                 jObj.addProperty(product.relURI, (Boolean) product.value);
66             }
67             if (product.value instanceof String) {
68                 jObj.addProperty(product.relURI, (String) product.value);
69             }
70             if (product.value instanceof List) {
71                 jObj.add(product.relURI, new Gson().toJsonTree(product.value));
72             }
73             return jObj;
74         }
75     }
76 }