]> git.basschouten.com Git - openhab-addons.git/blob
0e403d495a5c18e8286d1574d673fc23defe0735
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2023 Contributors to the openHAB project
3  *
4  * See the NOTICE file(s) distributed with this work for additional
5  * information.
6  *
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
10  *
11  * SPDX-License-Identifier: EPL-2.0
12  */
13 package org.openhab.binding.freeboxos.internal.api.deserialization;
14
15 import java.lang.reflect.ParameterizedType;
16 import java.lang.reflect.Type;
17 import java.util.ArrayList;
18 import java.util.List;
19
20 import org.eclipse.jdt.annotation.NonNull;
21 import org.eclipse.jdt.annotation.NonNullByDefault;
22 import org.eclipse.jdt.annotation.Nullable;
23
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;
30
31 /**
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.
34  *
35  * @author GaĆ«l L'hopital - Initial contribution
36  */
37 @NonNullByDefault
38 public class ListDeserializer implements JsonDeserializer<List<?>> {
39
40     @Override
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);
46
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));
53                     }
54                     return result;
55                 }
56             }
57         }
58         return List.of();
59     }
60
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) {
67                 jsonArray.add(json);
68             }
69             return jsonArray;
70         }
71         return null;
72     }
73 }