2 * Copyright (c) 2010-2020 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.gardena.internal.model.deser;
15 import java.lang.reflect.Type;
17 import org.apache.commons.lang.StringUtils;
18 import org.openhab.binding.gardena.internal.model.PropertyValue;
19 import org.slf4j.Logger;
20 import org.slf4j.LoggerFactory;
22 import com.google.gson.JsonArray;
23 import com.google.gson.JsonDeserializationContext;
24 import com.google.gson.JsonDeserializer;
25 import com.google.gson.JsonElement;
26 import com.google.gson.JsonObject;
27 import com.google.gson.JsonParseException;
30 * Custom deserializer for Gardena complex property value type.
32 * @author Gerhard Riegler - Initial contribution
34 public class PropertyValueDeserializer implements JsonDeserializer<PropertyValue> {
35 private final Logger logger = LoggerFactory.getLogger(PropertyValueDeserializer.class);
37 private static final String PROPERTY_DURATION = "duration";
38 private static final String PROPERTY_TYPE = "type";
39 private static final String PROPERTY_MAC = "mac";
40 private static final String PROPERTY_ISCONNECTED = "isconnected";
43 public PropertyValue deserialize(JsonElement element, Type type, JsonDeserializationContext ctx)
44 throws JsonParseException {
45 if (element.isJsonObject()) {
46 JsonObject jsonObj = element.getAsJsonObject();
47 if (jsonObj.has(PROPERTY_DURATION)) {
48 long duration = jsonObj.get(PROPERTY_DURATION).getAsLong();
50 duration = Math.round(duration / 60.0);
52 return new PropertyValue(String.valueOf(duration));
53 } else if (jsonObj.has(PROPERTY_TYPE)) {
54 return new PropertyValue(jsonObj.get(PROPERTY_TYPE).getAsString());
55 } else if (jsonObj.has(PROPERTY_MAC) && jsonObj.has(PROPERTY_ISCONNECTED)) {
56 // ignore known gateway properties
57 return new PropertyValue();
59 logger.warn("Unsupported json value object, returning empty value");
60 return new PropertyValue();
63 } else if (element.isJsonArray()) {
64 JsonArray jsonArray = element.getAsJsonArray();
65 return new PropertyValue(StringUtils.join(jsonArray.iterator(), ","));
67 return new PropertyValue(element.getAsString());