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.mqtt.homeassistant.internal.config;
15 import java.io.IOException;
16 import java.util.ArrayList;
17 import java.util.List;
18 import java.util.Objects;
20 import org.eclipse.jdt.annotation.NonNullByDefault;
21 import org.eclipse.jdt.annotation.Nullable;
23 import com.google.gson.TypeAdapter;
24 import com.google.gson.stream.JsonReader;
25 import com.google.gson.stream.JsonToken;
26 import com.google.gson.stream.JsonWriter;
29 * JsonTypeAdapter which will read a single string or a string list
31 * see: https://www.home-assistant.io/components/binary_sensor.mqtt/ -> device / identifiers
33 * @author Jochen Klein - Initial contribution
36 public class ListOrStringDeserializer extends TypeAdapter<List<String>> {
39 public void write(@Nullable JsonWriter out, @Nullable List<String> value) throws IOException {
40 Objects.requireNonNull(out);
48 for (String str : value) {
55 public @Nullable List<String> read(@Nullable JsonReader in) throws IOException {
56 Objects.requireNonNull(in);
58 JsonToken peek = in.peek();
65 return List.of(in.nextString());
69 throw new IOException("unexpected token " + peek + ". Array of string or string expected");
73 private List<String> readList(JsonReader in) throws IOException {
76 List<String> result = new ArrayList<>();
78 JsonToken peek = in.peek();
80 while (peek != JsonToken.END_ARRAY) {
81 if (peek == JsonToken.STRING) {
82 result.add(in.nextString());
84 throw new IOException("unexpected token " + peek + ". Array of string or string expected");