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.nikohomecontrol.internal.protocol.nhc1;
15 import java.lang.reflect.Type;
16 import java.util.ArrayList;
17 import java.util.HashMap;
18 import java.util.List;
20 import java.util.Map.Entry;
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 * Class {@link NikoHomeControlMessageDeserializer1} deserializes all json messages from Niko Home Control. Various json
31 * message formats are supported. The format is selected based on the content of the cmd and event json objects.
33 * @author Mark Herwege - Initial Contribution
36 class NikoHomeControlMessageDeserializer1 implements JsonDeserializer<NhcMessageBase1> {
39 public NhcMessageBase1 deserialize(final JsonElement json, final Type typeOfT,
40 final JsonDeserializationContext context) throws JsonParseException {
41 final JsonObject jsonObject = json.getAsJsonObject();
46 if (jsonObject.has("cmd")) {
47 cmd = jsonObject.get("cmd").getAsString();
49 if (jsonObject.has("event")) {
50 event = jsonObject.get("event").getAsString();
53 JsonElement jsonData = null;
54 if (jsonObject.has("data")) {
55 jsonData = jsonObject.get("data");
58 NhcMessageBase1 message = null;
60 if (jsonData != null) {
61 if (jsonData.isJsonObject()) {
62 message = new NhcMessageMap1();
64 Map<String, String> data = new HashMap<>();
65 for (Entry<String, JsonElement> entry : jsonData.getAsJsonObject().entrySet()) {
66 data.put(entry.getKey(), entry.getValue().getAsString());
68 ((NhcMessageMap1) message).setData(data);
70 } else if (jsonData.isJsonArray()) {
71 JsonArray jsonDataArray = jsonData.getAsJsonArray();
73 message = new NhcMessageListMap1();
75 List<Map<String, String>> dataList = new ArrayList<>();
76 for (int i = 0; i < jsonDataArray.size(); i++) {
77 JsonObject jsonDataObject = jsonDataArray.get(i).getAsJsonObject();
79 Map<String, String> data = new HashMap<>();
80 for (Entry<String, JsonElement> entry : jsonDataObject.entrySet()) {
81 data.put(entry.getKey(), entry.getValue().getAsString());
85 ((NhcMessageListMap1) message).setData(dataList);
89 if (message != null) {
91 message.setEvent(event);
93 throw new JsonParseException("Unexpected Json type");
98 } catch (IllegalStateException | ClassCastException e) {
99 throw new JsonParseException("Unexpected Json type");