2 * Copyright (c) 2010-2022 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 RioFavorite}. Simply writes/reads the ID and
27 * name to elements called "id", "valid" and "name"
29 * @author Tim Roberts - Initial contribution
31 public class RioFavoriteSerializer implements JsonSerializer<RioFavorite>, JsonDeserializer<RioFavorite> {
34 * Overridden to simply write out the id/valid/name elements from the {@link RioFavorite}
36 * @param favorite the {@link RioFavorite} to write out
37 * @param type the type
38 * @param context the serialization context
41 public JsonElement serialize(RioFavorite favorite, Type type, JsonSerializationContext context) {
42 JsonObject root = new JsonObject();
43 root.addProperty("id", favorite.getId());
44 root.addProperty("valid", favorite.isValid());
45 root.addProperty("name", favorite.getName());
51 * Overridden to simply read the id/valid/name elements and create a {@link RioFavorite}
53 * @param elm the {@link JsonElement} to read from
54 * @param type the type
55 * @param context the serialization context
58 public RioFavorite deserialize(JsonElement elm, Type type, JsonDeserializationContext context)
59 throws JsonParseException {
60 final JsonObject jo = (JsonObject) elm;
62 final JsonElement id = jo.get("id");
63 final JsonElement valid = jo.get("valid");
64 final JsonElement name = jo.get("name");
66 return new RioFavorite((id == null ? -1 : id.getAsInt()), (valid == null ? false : valid.getAsBoolean()),
67 (name == null ? null : name.getAsString()));