]> git.basschouten.com Git - openhab-addons.git/blob
01c78712d92ad5def5e0200de2cf155bb2f4a0d6
[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.binding.mqtt.homeassistant.internal.config;
14
15 import java.io.IOException;
16 import java.util.ArrayList;
17 import java.util.List;
18 import java.util.Objects;
19
20 import org.eclipse.jdt.annotation.NonNullByDefault;
21 import org.eclipse.jdt.annotation.Nullable;
22
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;
27
28 /**
29  * JsonTypeAdapter which will read a single string or a string list
30  *
31  * see: https://www.home-assistant.io/components/binary_sensor.mqtt/ -> device / identifiers
32  *
33  * @author Jochen Klein - Initial contribution
34  */
35 @NonNullByDefault
36 public class ListOrStringDeserializer extends TypeAdapter<List<String>> {
37
38     @Override
39     public void write(@Nullable JsonWriter out, @Nullable List<String> value) throws IOException {
40         Objects.requireNonNull(out);
41
42         if (value == null) {
43             out.nullValue();
44             return;
45         }
46
47         out.beginArray();
48         for (String str : value) {
49             out.jsonValue(str);
50         }
51         out.endArray();
52     }
53
54     @Override
55     public @Nullable List<String> read(@Nullable JsonReader in) throws IOException {
56         Objects.requireNonNull(in);
57
58         JsonToken peek = in.peek();
59
60         switch (peek) {
61             case NULL:
62                 in.nextNull();
63                 return null;
64             case STRING:
65                 return List.of(in.nextString());
66             case BEGIN_ARRAY:
67                 return readList(in);
68             default:
69                 throw new IOException("unexpected token " + peek + ". Array of string or string expected");
70         }
71     }
72
73     private List<String> readList(JsonReader in) throws IOException {
74         in.beginArray();
75
76         List<String> result = new ArrayList<>();
77
78         JsonToken peek = in.peek();
79
80         while (peek != JsonToken.END_ARRAY) {
81             if (peek == JsonToken.STRING) {
82                 result.add(in.nextString());
83             } else {
84                 throw new IOException("unexpected token " + peek + ". Array of string or string expected");
85             }
86             peek = in.peek();
87         }
88         in.endArray();
89
90         return result;
91     }
92 }