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.sensibo.internal;
15 import static org.junit.jupiter.api.Assertions.assertEquals;
17 import java.io.IOException;
18 import java.lang.reflect.Type;
19 import java.nio.charset.StandardCharsets;
20 import java.time.ZonedDateTime;
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 = new String(WireHelper.class.getResourceAsStream(jsonClasspathName).readAllBytes(),
55 StandardCharsets.UTF_8);
57 final JsonObject o = JsonParser.parseString(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 = new String(WireHelper.class.getResourceAsStream(jsonClasspathName).readAllBytes(),
65 StandardCharsets.UTF_8);
66 return deSerializeFromString(json, type);
69 public <T> T deSerializeFromString(final String json, final Type type) throws IOException {
70 return gson.fromJson(json, type);
73 public <T> String serialize(final AbstractRequest req) throws IOException {
74 return gson.toJson(req);