]> git.basschouten.com Git - openhab-addons.git/blob
8ccef5f80f711c0b56ddb481df5d1466459a0b73
[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.netatmo.internal.deserialization;
14
15 import java.lang.reflect.ParameterizedType;
16 import java.lang.reflect.Type;
17
18 import org.eclipse.jdt.annotation.NonNullByDefault;
19 import org.eclipse.jdt.annotation.Nullable;
20 import org.openhab.binding.netatmo.internal.api.dto.NAObject;
21
22 import com.google.gson.JsonArray;
23 import com.google.gson.JsonDeserializationContext;
24 import com.google.gson.JsonDeserializer;
25 import com.google.gson.JsonElement;
26 import com.google.gson.JsonParseException;
27
28 /**
29  * The {@link NAObjectMapDeserializer} is a specialized deserializer aimed to transform
30  * a list of `NAObjects` into a map identified by the object's id.
31  *
32  * @author GaĆ«l L'hopital - Initial contribution
33  */
34 @NonNullByDefault
35 class NAObjectMapDeserializer implements JsonDeserializer<NAObjectMap<?>> {
36     @Override
37     public @Nullable NAObjectMap<?> deserialize(JsonElement json, Type clazz, JsonDeserializationContext context)
38             throws JsonParseException {
39         ParameterizedType parameterized = (ParameterizedType) clazz;
40         Type[] typeArguments = parameterized.getActualTypeArguments();
41         if (typeArguments.length > 0 && json instanceof JsonArray) {
42             Type objectType = typeArguments[0];
43             NAObjectMap<NAObject> result = new NAObjectMap<>();
44             ((JsonArray) json).forEach(item -> {
45                 result.put(context.deserialize(item, objectType));
46             });
47             return result;
48         }
49         return null;
50     }
51 }