]> git.basschouten.com Git - openhab-addons.git/blob
210a80e66b3cf270ad312c096b59dc1ca2c2bc42
[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.tankerkoenig.internal.serializer;
14
15 import java.lang.reflect.Type;
16 import java.util.ArrayList;
17 import java.util.List;
18 import java.util.Map.Entry;
19 import java.util.Set;
20
21 import org.openhab.binding.tankerkoenig.internal.dto.LittleStation;
22 import org.openhab.binding.tankerkoenig.internal.dto.Prices;
23 import org.openhab.binding.tankerkoenig.internal.dto.TankerkoenigListResult;
24
25 import com.google.gson.Gson;
26 import com.google.gson.JsonDeserializationContext;
27 import com.google.gson.JsonDeserializer;
28 import com.google.gson.JsonElement;
29 import com.google.gson.JsonObject;
30 import com.google.gson.JsonParseException;
31
32 /***
33  * Custom Deserializer fopr the list result of tankerkoenigs api response
34  *
35  * @author Dennis Dollinger - Initial contribution
36  */
37 public class CustomTankerkoenigListResultDeserializer implements JsonDeserializer<TankerkoenigListResult> {
38
39     private final Gson gson = new Gson();
40
41     @Override
42     public TankerkoenigListResult deserialize(final JsonElement json, final Type typeOfT,
43             final JsonDeserializationContext context) throws JsonParseException {
44         final JsonObject jsonObject = json.getAsJsonObject();
45
46         final Boolean isOK = jsonObject.get("ok").getAsBoolean();
47         TankerkoenigListResult result = new TankerkoenigListResult();
48         if (isOK) {
49             result.setOk(jsonObject.get("ok").getAsBoolean());
50             JsonObject jsonPrices = jsonObject.get("prices").getAsJsonObject();
51             Set<Entry<String, JsonElement>> objects = jsonPrices.entrySet();
52             Prices p = new Prices();
53             result.setPrices(p);
54             List<LittleStation> list = new ArrayList<>();
55             for (Entry<String, JsonElement> entry : objects) {
56                 JsonElement jsonElement = entry.getValue();
57                 LittleStation station = gson.fromJson(jsonElement, LittleStation.class);
58                 station.setID(entry.getKey());
59                 list.add(station);
60             }
61             result.getPrices().setStations(list);
62         } else {
63             result.setOk(jsonObject.get("ok").getAsBoolean());
64             result.setMessage(jsonObject.get("message").getAsString());
65         }
66         return result;
67     }
68 }