From 77ce96dba14a474dfdc1522d4bc16fc3167d1559 Mon Sep 17 00:00:00 2001 From: Yannik Bretschneider Date: Thu, 3 Jun 2021 23:08:01 +0200 Subject: [PATCH] feat: changed JSON return types to optionals --- .../marvelous/gamelibrary/json/JSON.java | 25 +++++++++++-------- 1 file changed, 14 insertions(+), 11 deletions(-) diff --git a/src/main/java/uulm/teamname/marvelous/gamelibrary/json/JSON.java b/src/main/java/uulm/teamname/marvelous/gamelibrary/json/JSON.java index 2063b2e..eaf5cf7 100644 --- a/src/main/java/uulm/teamname/marvelous/gamelibrary/json/JSON.java +++ b/src/main/java/uulm/teamname/marvelous/gamelibrary/json/JSON.java @@ -7,6 +7,8 @@ import uulm.teamname.marvelous.gamelibrary.config.CharacterConfig; import uulm.teamname.marvelous.gamelibrary.messages.BasicMessage; import uulm.teamname.marvelous.gamelibrary.messages.server.EventMessage; +import java.util.Optional; + /** * Class that contains JSON encoding and decoding. It is initiated with the Character configuration. */ @@ -23,29 +25,30 @@ public class JSON { /** Deserializes an incoming network message into a {@link EventMessage}. * @param input The JSON to deserialize - * @return The parsed message (as {@link BasicMessage}, so casting is necessary) - * or {@code null} if the deserialization failed + * @return An {@link Optional} containing the parsed message (as {@link BasicMessage}, so typecasting is necessary) + * or an empty {@link Optional} if the deserialization failed */ - public BasicMessage parse(String input) { + public Optional parse(String input) { BasicMessage result = null; try { - return mapper.readValue(input, BasicMessage.class); + return Optional.of(mapper.readValue(input, BasicMessage.class)); } catch (JsonProcessingException e) { - // e.printStackTrace(); - return null; + e.printStackTrace(); + return Optional.empty(); } } /** Serializes a {@link EventMessage} into a JSON string. * @param input The message to serialize - * @return The message as JSON or {@code null} if the serialization failed + * @return An {@link Optional}<{@link String}> of the message as JSON or + * an empty {@link Optional} if the serialization failed */ - public String stringify(BasicMessage input) { + public Optional stringify(BasicMessage input) { try { - return mapper.writeValueAsString(input); + return Optional.of(mapper.writeValueAsString(input)); } catch (JsonProcessingException e) { - // e.printStackTrace(); - return null; + e.printStackTrace(); + return Optional.empty(); } } }