]> git.basschouten.com Git - openhab-addons.git/blob
1144a36d45c2d1570cca6ab9f297a8f00253c262
[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.russound.internal.rio.models;
14
15 import java.io.IOException;
16 import java.util.concurrent.atomic.AtomicReference;
17
18 import com.google.gson.JsonElement;
19 import com.google.gson.JsonObject;
20 import com.google.gson.JsonParser;
21 import com.google.gson.JsonPrimitive;
22 import com.google.gson.TypeAdapter;
23 import com.google.gson.stream.JsonReader;
24 import com.google.gson.stream.JsonWriter;
25
26 /**
27  * A GSON {@link TypeAdapter} that will properly write/read {@link AtomicReference} strings
28  *
29  * @author Tim Roberts - Initial contribution
30  */
31 public class AtomicStringTypeAdapter extends TypeAdapter<AtomicReference<String>> {
32
33     /**
34      * Overriden to read the string from the {@link JsonReader} and create an
35      * {@link AtomicReference} from it
36      */
37     @Override
38     public AtomicReference<String> read(JsonReader in) throws IOException {
39         AtomicReference<String> value = null;
40
41         JsonElement je = JsonParser.parseReader(in);
42
43         if (je instanceof JsonPrimitive jsonPrimitive) {
44             value = new AtomicReference<>();
45             value.set(jsonPrimitive.getAsString());
46         } else if (je instanceof JsonObject jsonObject) {
47             value = new AtomicReference<>();
48             value.set(jsonObject.get("value").getAsString());
49         }
50
51         return value;
52     }
53
54     /**
55      * Overridden to write out the underlying string
56      */
57     @Override
58     public void write(JsonWriter out, AtomicReference<String> value) throws IOException {
59         if (value != null) {
60             out.value(value.get());
61         }
62     }
63 }