]> git.basschouten.com Git - openhab-addons.git/blob
54a1a5bd1f46662972254c8eeccdce1048371846
[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) {
44             value = new AtomicReference<>();
45             value.set(((JsonPrimitive) je).getAsString());
46         } else if (je instanceof JsonObject) {
47             JsonObject jsonObject = (JsonObject) je;
48             value = new AtomicReference<>();
49             value.set(jsonObject.get("value").getAsString());
50         }
51
52         return value;
53     }
54
55     /**
56      * Overridden to write out the underlying string
57      */
58     @Override
59     public void write(JsonWriter out, AtomicReference<String> value) throws IOException {
60         if (value != null) {
61             out.value(value.get());
62         }
63     }
64 }