2 * Copyright (c) 2010-2020 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.Collections;
17 import java.util.List;
19 import org.openhab.core.types.State;
20 import org.openhab.core.types.TypeParser;
21 import org.slf4j.Logger;
22 import org.slf4j.LoggerFactory;
24 import com.google.gson.TypeAdapter;
25 import com.google.gson.stream.JsonReader;
26 import com.google.gson.stream.JsonToken;
27 import com.google.gson.stream.JsonWriter;
30 * A GSON TypeAdapter for openHAB State values.
32 * @author Martin Kühl - Initial contribution
34 public class StateTypeAdapter extends TypeAdapter<State> {
35 private static final String TYPE_SEPARATOR = "@@@";
37 private final Logger logger = LoggerFactory.getLogger(StateTypeAdapter.class);
40 public State read(JsonReader reader) throws IOException {
41 if (reader.peek() == JsonToken.NULL) {
45 String value = reader.nextString();
46 String[] parts = value.split(TYPE_SEPARATOR);
47 String valueTypeName = parts[0];
48 String valueAsString = parts[1];
51 @SuppressWarnings("unchecked")
52 Class<? extends State> valueType = (Class<? extends State>) Class.forName(valueTypeName);
53 List<Class<? extends State>> types = Collections.singletonList(valueType);
54 return TypeParser.parseState(types, valueAsString);
55 } catch (Exception e) {
56 logger.warn("Couldn't deserialize state '{}': {}", value, e.getMessage());
62 public void write(JsonWriter writer, State state) throws IOException {
67 String value = state.getClass().getName() + TYPE_SEPARATOR + state.toFullString();