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