2 * Copyright (c) 2010-2020 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.sensibo.internal;
15 import static org.junit.jupiter.api.Assertions.*;
17 import java.io.IOException;
18 import java.lang.reflect.Type;
19 import java.time.ZonedDateTime;
21 import org.apache.commons.io.IOUtils;
22 import org.openhab.binding.sensibo.internal.dto.AbstractRequest;
24 import com.google.gson.Gson;
25 import com.google.gson.GsonBuilder;
26 import com.google.gson.JsonObject;
27 import com.google.gson.JsonParser;
28 import com.google.gson.TypeAdapter;
29 import com.google.gson.stream.JsonReader;
30 import com.google.gson.stream.JsonWriter;
33 * @author Arne Seime - Initial contribution
35 public class WireHelper {
37 private final Gson gson;
40 gson = new GsonBuilder().registerTypeAdapter(ZonedDateTime.class, new TypeAdapter<ZonedDateTime>() {
42 public void write(final JsonWriter out, final ZonedDateTime value) throws IOException {
43 out.value(value.toString());
47 public ZonedDateTime read(final JsonReader in) throws IOException {
48 return ZonedDateTime.parse(in.nextString());
50 }).setPrettyPrinting().create();
53 public <T> T deSerializeResponse(final String jsonClasspathName, final Type type) throws IOException {
54 final String json = IOUtils.toString(WireHelper.class.getResourceAsStream(jsonClasspathName));
56 final JsonParser parser = new JsonParser();
57 final JsonObject o = parser.parse(json).getAsJsonObject();
58 assertEquals("success", o.get("status").getAsString());
60 return gson.fromJson(o.get("result"), type);
63 public <T> T deSerializeFromClasspathResource(final String jsonClasspathName, final Type type) throws IOException {
64 final String json = IOUtils.toString(WireHelper.class.getResourceAsStream(jsonClasspathName));
65 return deSerializeFromString(json, type);
68 public <T> T deSerializeFromString(final String json, final Type type) throws IOException {
69 return gson.fromJson(json, type);
72 public <T> String serialize(final AbstractRequest req) throws IOException {
73 return gson.toJson(req);