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.freeboxos.internal.api.deserialization;
15 import java.lang.reflect.ParameterizedType;
16 import java.lang.reflect.Type;
17 import java.util.ArrayList;
18 import java.util.List;
20 import org.eclipse.jdt.annotation.NonNull;
21 import org.eclipse.jdt.annotation.NonNullByDefault;
22 import org.eclipse.jdt.annotation.Nullable;
24 import com.google.gson.JsonArray;
25 import com.google.gson.JsonDeserializationContext;
26 import com.google.gson.JsonDeserializer;
27 import com.google.gson.JsonElement;
28 import com.google.gson.JsonObject;
29 import com.google.gson.JsonParseException;
32 * The {@link ListDeserializer} is a specialized deserializer aimed to transform a null object, a single object or
33 * a list of objects into a list containing 0, 1 or n elements.
35 * @author Gaƫl L'hopital - Initial contribution
38 public class ListDeserializer implements JsonDeserializer<List<?>> {
41 public @NonNull List<?> deserialize(@Nullable JsonElement json, @Nullable Type clazz,
42 @Nullable JsonDeserializationContext context) throws JsonParseException {
43 if (json != null && clazz != null && context != null) {
44 JsonArray jsonArray = toJsonArray(json);
45 ArrayList<?> result = new ArrayList<>(jsonArray != null ? jsonArray.size() : 0);
47 if (jsonArray != null) {
48 Type[] typeArguments = ((ParameterizedType) clazz).getActualTypeArguments();
49 if (typeArguments.length > 0) {
50 Type objectType = typeArguments[0];
51 for (int i = 0; i < jsonArray.size(); i++) {
52 result.add(context.deserialize(jsonArray.get(i), objectType));
61 private @Nullable JsonArray toJsonArray(JsonElement json) {
62 if (json instanceof JsonArray) {
63 return json.getAsJsonArray();
64 } else if (json instanceof JsonObject) {
65 JsonArray jsonArray = new JsonArray();
66 if (json.getAsJsonObject().size() > 0) {