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.persistence.mapdb.internal;
15 import java.io.IOException;
16 import java.util.List;
18 import org.openhab.core.types.State;
19 import org.openhab.core.types.TypeParser;
20 import org.slf4j.Logger;
21 import org.slf4j.LoggerFactory;
23 import com.google.gson.TypeAdapter;
24 import com.google.gson.stream.JsonReader;
25 import com.google.gson.stream.JsonToken;
26 import com.google.gson.stream.JsonWriter;
29 * A GSON TypeAdapter for openHAB State values.
31 * @author Martin Kühl - Initial contribution
33 public class StateTypeAdapter extends TypeAdapter<State> {
34 private static final String TYPE_SEPARATOR = "@@@";
36 private final Logger logger = LoggerFactory.getLogger(StateTypeAdapter.class);
39 public State read(JsonReader reader) throws IOException {
40 if (reader.peek() == JsonToken.NULL) {
44 String value = reader.nextString();
47 int index = value.indexOf(TYPE_SEPARATOR);
49 logger.warn("Couldn't deserialize state '{}': type separator '{}' not found", value, TYPE_SEPARATOR);
52 String valueTypeName = value.substring(0, index);
53 String valueAsString = value.substring(index + TYPE_SEPARATOR.length());
55 @SuppressWarnings("unchecked")
56 Class<? extends State> valueType = (Class<? extends State>) Class.forName(valueTypeName);
57 return TypeParser.parseState(List.of(valueType), valueAsString);
58 } catch (Exception e) {
59 logger.warn("Couldn't deserialize state '{}': {}", value, e.getMessage());
65 public void write(JsonWriter writer, State state) throws IOException {
70 String value = state.getClass().getName() + TYPE_SEPARATOR + state.toFullString();