]> git.basschouten.com Git - openhab-addons.git/blob
53530dc6a62e3ca790c3e1880bd799074f83017c
[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.lang.reflect.Type;
16
17 import com.google.gson.JsonDeserializationContext;
18 import com.google.gson.JsonDeserializer;
19 import com.google.gson.JsonElement;
20 import com.google.gson.JsonObject;
21 import com.google.gson.JsonParseException;
22 import com.google.gson.JsonSerializationContext;
23 import com.google.gson.JsonSerializer;
24
25 /**
26  * A {@link JsonSerializer} and {@link JsonDeserializer} for the {@link RioBank}. Simply writes/reads the ID and name to
27  * elements called "id" and "name"
28  *
29  * @author Tim Roberts - Initial contribution
30  */
31 public class RioBankSerializer implements JsonSerializer<RioBank>, JsonDeserializer<RioBank> {
32
33     /**
34      * Overridden to simply write out the id/name elements from the {@link RioBank}
35      *
36      * @param bank the {@link RioBank} to write out
37      * @param type the type
38      * @param context the serialization context
39      */
40     @Override
41     public JsonElement serialize(RioBank bank, Type type, JsonSerializationContext context) {
42         JsonObject root = new JsonObject();
43         root.addProperty("id", bank.getId());
44         root.addProperty("name", bank.getName());
45
46         return root;
47     }
48
49     /**
50      * Overridden to simply read the id/name elements and create a {@link RioBank}
51      *
52      * @param elm the {@link JsonElement} to read from
53      * @param type the type
54      * @param context the serialization context
55      */
56     @Override
57     public RioBank deserialize(JsonElement elm, Type type, JsonDeserializationContext context)
58             throws JsonParseException {
59         final JsonObject jo = (JsonObject) elm;
60
61         final JsonElement id = jo.get("id");
62         final JsonElement name = jo.get("name");
63         return new RioBank((id == null ? -1 : id.getAsInt()), (name == null ? null : name.getAsString()));
64     }
65 }