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.gpstracker.internal.message;
15 import java.util.HashMap;
18 import org.eclipse.jdt.annotation.NonNullByDefault;
19 import org.eclipse.jdt.annotation.Nullable;
20 import org.openhab.binding.gpstracker.internal.message.dto.LocationMessage;
21 import org.openhab.binding.gpstracker.internal.message.dto.TransitionMessage;
23 import com.google.gson.Gson;
26 * Message handling utility
28 * @author Gabor Bicskei - Initial contribution
31 public class MessageUtil {
33 * Patterns to identify incoming JSON payload.
35 private static final String[] PATTERNS = new String[] { ".*\"_type\"\\s*:\\s*\"transition\".*", // transition
36 ".*\"_type\"\\s*:\\s*\"location\".*", // location
40 * Supported message types
42 private static final Map<String, Class<? extends LocationMessage>> MESSAGE_TYPES = new HashMap<>();
45 MESSAGE_TYPES.put(PATTERNS[0], TransitionMessage.class);
46 MESSAGE_TYPES.put(PATTERNS[1], LocationMessage.class);
49 private final Gson gson = new Gson();
52 * Parses JSON message into an object with type determined by message pattern.
54 * @param json JSON string.
55 * @return Parsed message POJO or null without pattern match
57 public @Nullable LocationMessage fromJson(String json) {
58 for (String pattern : PATTERNS) {
59 Class<? extends LocationMessage> c = MESSAGE_TYPES.get(pattern);
60 if (c != null && json.matches(pattern)) {
61 return gson.fromJson(json, c);
68 * Converts object to JSON sting.
70 * @param o Object to convert
73 public String toJson(Object o) {
74 return gson.toJson(o);