2 * Copyright (c) 2010-2023 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 org.eclipse.jdt.annotation.NonNullByDefault;
23 import org.eclipse.jdt.annotation.Nullable;
25 import com.google.gson.JsonArray;
26 import com.google.gson.JsonDeserializationContext;
27 import com.google.gson.JsonDeserializer;
28 import com.google.gson.JsonElement;
29 import com.google.gson.JsonObject;
30 import com.google.gson.JsonParseException;
33 * Class {@link NikoHomeControlMessageDeserializer1} deserializes all json messages from Niko Home Control. Various json
34 * message formats are supported. The format is selected based on the content of the cmd and event json objects.
36 * @author Mark Herwege - Initial Contribution
40 class NikoHomeControlMessageDeserializer1 implements JsonDeserializer<NhcMessageBase1> {
43 public @Nullable NhcMessageBase1 deserialize(final JsonElement json, final Type typeOfT,
44 final JsonDeserializationContext context) throws JsonParseException {
45 final JsonObject jsonObject = json.getAsJsonObject();
50 if (jsonObject.has("cmd")) {
51 cmd = jsonObject.get("cmd").getAsString();
53 if (jsonObject.has("event")) {
54 event = jsonObject.get("event").getAsString();
57 JsonElement jsonData = null;
58 if (jsonObject.has("data")) {
59 jsonData = jsonObject.get("data");
62 NhcMessageBase1 message = null;
64 if (jsonData != null) {
65 if (jsonData.isJsonObject()) {
66 message = new NhcMessageMap1();
68 Map<String, String> data = new HashMap<>();
69 for (Entry<String, JsonElement> entry : jsonData.getAsJsonObject().entrySet()) {
70 data.put(entry.getKey(), entry.getValue().getAsString());
72 ((NhcMessageMap1) message).setData(data);
74 } else if (jsonData.isJsonArray()) {
75 JsonArray jsonDataArray = jsonData.getAsJsonArray();
77 message = new NhcMessageListMap1();
79 List<Map<String, String>> dataList = new ArrayList<>();
80 for (int i = 0; i < jsonDataArray.size(); i++) {
81 JsonObject jsonDataObject = jsonDataArray.get(i).getAsJsonObject();
83 Map<String, String> data = new HashMap<>();
84 for (Entry<String, JsonElement> entry : jsonDataObject.entrySet()) {
85 data.put(entry.getKey(), entry.getValue().getAsString());
89 ((NhcMessageListMap1) message).setData(dataList);
93 if (message != null) {
95 message.setEvent(event);
97 throw new JsonParseException("Unexpected Json type");
102 } catch (IllegalStateException | ClassCastException e) {
103 throw new JsonParseException("Unexpected Json type");