2 * Copyright 2017-2018 Gregory Moyer and contributors.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
16 package org.openhab.binding.lametrictime.api.common.impl.typeadapters;
18 import java.util.ArrayList;
19 import java.util.List;
20 import java.util.Map.Entry;
22 import org.openhab.binding.lametrictime.api.common.impl.typeadapters.imported.CustomizedTypeAdapterFactory;
23 import org.openhab.binding.lametrictime.api.local.model.Action;
25 import com.google.gson.JsonElement;
26 import com.google.gson.JsonObject;
28 public class ActionTypeAdapterFactory extends CustomizedTypeAdapterFactory<Action>
30 private static final String PROPERTY_ID = "id";
31 private static final String PROPERTY_PARAMETERS = "params";
33 public ActionTypeAdapterFactory()
39 protected void beforeWrite(Action source, JsonElement toSerialize)
41 if (toSerialize == null || toSerialize.isJsonNull())
46 JsonObject actionObj = toSerialize.getAsJsonObject();
47 if (actionObj == null || actionObj.isJsonNull())
52 // rewrite parameters from a nested object (map) to properties on the action
53 JsonElement paramsElem = actionObj.get(PROPERTY_PARAMETERS);
54 if (paramsElem != null && !paramsElem.isJsonNull())
56 JsonObject paramsObj = paramsElem.getAsJsonObject();
57 actionObj.remove(PROPERTY_PARAMETERS);
59 for (Entry<String, JsonElement> entry : paramsObj.entrySet())
61 actionObj.add(entry.getKey(), entry.getValue());
67 protected void afterRead(JsonElement deserialized)
69 if (deserialized == null || deserialized.isJsonNull())
74 JsonObject actionObj = deserialized.getAsJsonObject();
75 if (actionObj == null || actionObj.isJsonNull())
80 if (actionObj.has(PROPERTY_PARAMETERS))
82 throw new IllegalArgumentException("Attempting to deserialize Action that contains a colliding "
87 // temporary list of field names
88 List<String> fields = new ArrayList<>();
90 // rewrite parameters to a nested object (map)
91 JsonObject paramsObj = new JsonObject();
92 for (Entry<String, JsonElement> entry : actionObj.entrySet())
95 if (PROPERTY_ID.equals(entry.getKey()))
100 String paramId = entry.getKey();
101 fields.add(paramId); // to be removed later
103 paramsObj.add(paramId, entry.getValue());
105 actionObj.add(PROPERTY_PARAMETERS, paramsObj);
107 // remove all fields other than the list
108 fields.forEach(field -> actionObj.remove(field));