2 * Copyright (c) 2010-2023 Contributors to the openHAB project
4 * See the NOTICE file(s) distributed with this work for additional
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
11 * SPDX-License-Identifier: EPL-2.0
13 package org.openhab.binding.russound.internal.rio.models;
15 import java.lang.reflect.Type;
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;
26 * A {@link JsonSerializer} and {@link JsonDeserializer} for the {@link RioPreset}. Simply writes/reads the ID and
27 * name to elements called "id", "valid", "name", "bank" and "bankPreset" values.
29 * @author Tim Roberts - Initial contribution
31 public class RioPresetSerializer implements JsonSerializer<RioPreset>, JsonDeserializer<RioPreset> {
34 * Overridden to simply write out the id/valid/name/bank/bankPreset elements from the {@link RioPreset}
36 * @param preset the {@link RioPreset} to write out
37 * @param type the type
38 * @param context the serialization context
41 public JsonElement serialize(RioPreset preset, Type type, JsonSerializationContext context) {
42 JsonObject root = new JsonObject();
43 root.addProperty("id", preset.getId());
44 root.addProperty("valid", preset.isValid());
45 root.addProperty("name", preset.getName());
46 root.addProperty("bank", preset.getBank());
47 root.addProperty("bankPreset", preset.getBankPreset());
53 * Overridden to simply read the id/valid/name elements and create a {@link RioPreset}. Please note that
54 * the bank/bankPreset are calculated fields from the ID and do not need to be read.
56 * @param elm the {@link JsonElement} to read from
57 * @param type the type
58 * @param context the serialization context
61 public RioPreset deserialize(JsonElement elm, Type type, JsonDeserializationContext context)
62 throws JsonParseException {
63 final JsonObject jo = (JsonObject) elm;
64 final JsonElement id = jo.get("id");
65 final JsonElement valid = jo.get("valid");
66 final JsonElement name = jo.get("name");
68 return new RioPreset((id == null ? -1 : id.getAsInt()), (valid == null ? false : valid.getAsBoolean()),
69 (name == null ? null : name.getAsString()));