2 * Copyright (c) 2010-2022 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.digitalstrom.internal.lib.serverconnection.impl;
15 import org.openhab.binding.digitalstrom.internal.lib.serverconnection.constants.JSONApiResponseKeysEnum;
16 import org.slf4j.Logger;
17 import org.slf4j.LoggerFactory;
19 import com.google.gson.JsonObject;
20 import com.google.gson.JsonParseException;
21 import com.google.gson.JsonParser;
24 * The {@link JSONResponseHandler} checks a digitalSTROM-JSON response and can parse it to a {@link JsonObject}.
26 * @author Alexander Betker - Initial contribution
27 * @author Alex Maier - Initial contribution
28 * @author Michael Ochel - add Java-Doc, make methods static and change from SimpleJSON to GSON
29 * @author Matthias Siegele - add Java-Doc, make methods static and change from SimpleJSON to GSON
31 public class JSONResponseHandler {
33 private static final Logger LOGGER = LoggerFactory.getLogger(JSONResponseHandler.class);
36 * Checks the digitalSTROM-JSON response and return true if it was successful, otherwise false.
38 * @param jsonResponse to check
39 * @return true, if successful
41 public static boolean checkResponse(JsonObject jsonResponse) {
42 if (jsonResponse == null) {
44 } else if (jsonResponse.get(JSONApiResponseKeysEnum.OK.getKey()) != null) {
45 return jsonResponse.get(JSONApiResponseKeysEnum.OK.getKey()).getAsBoolean();
47 String message = "unknown message";
48 if (jsonResponse.get(JSONApiResponseKeysEnum.MESSAGE.getKey()) != null) {
49 message = jsonResponse.get(JSONApiResponseKeysEnum.MESSAGE.getKey()).getAsString();
51 LOGGER.error("JSONResponseHandler: error in json request. Error message : {}", message);
57 * Returns the {@link JsonObject} from the given digitalSTROM-JSON response {@link String} or null if the json
60 * @param jsonResponse to convert
63 public static JsonObject toJsonObject(String jsonResponse) {
64 if (jsonResponse != null && !jsonResponse.trim().equals("")) {
66 return (JsonObject) JsonParser.parseString(jsonResponse);
67 } catch (JsonParseException e) {
68 LOGGER.error("A JsonParseException occurred by parsing jsonRequest: {}", jsonResponse, e);
75 * Returns the result {@link JsonObject} from the given digitalSTROM-JSON response {@link JsonObject}.
77 * @param jsonObject of response
78 * @return json result object
80 public static JsonObject getResultJsonObject(JsonObject jsonObject) {
81 if (jsonObject != null) {
82 return jsonObject.get(JSONApiResponseKeysEnum.RESULT.getKey()).getAsJsonObject();