feat: changed JSON return types to optionals

This commit is contained in:
Yannik Bretschneider 2021-06-03 23:08:01 +02:00
parent 445bde1105
commit 77ce96dba1

View File

@ -7,6 +7,8 @@ import uulm.teamname.marvelous.gamelibrary.config.CharacterConfig;
import uulm.teamname.marvelous.gamelibrary.messages.BasicMessage; import uulm.teamname.marvelous.gamelibrary.messages.BasicMessage;
import uulm.teamname.marvelous.gamelibrary.messages.server.EventMessage; 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. * 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}. /** Deserializes an incoming network message into a {@link EventMessage}.
* @param input The JSON to deserialize * @param input The JSON to deserialize
* @return The parsed message (as {@link BasicMessage}, so casting is necessary) * @return An {@link Optional} containing the parsed message (as {@link BasicMessage}, so typecasting is necessary)
* or {@code null} if the deserialization failed * or an empty {@link Optional} if the deserialization failed
*/ */
public BasicMessage parse(String input) { public Optional<BasicMessage> parse(String input) {
BasicMessage result = null; BasicMessage result = null;
try { try {
return mapper.readValue(input, BasicMessage.class); return Optional.of(mapper.readValue(input, BasicMessage.class));
} catch (JsonProcessingException e) { } catch (JsonProcessingException e) {
// e.printStackTrace(); e.printStackTrace();
return null; return Optional.empty();
} }
} }
/** Serializes a {@link EventMessage} into a JSON string. /** Serializes a {@link EventMessage} into a JSON string.
* @param input The message to serialize * @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<String> stringify(BasicMessage input) {
try { try {
return mapper.writeValueAsString(input); return Optional.of(mapper.writeValueAsString(input));
} catch (JsonProcessingException e) { } catch (JsonProcessingException e) {
// e.printStackTrace(); e.printStackTrace();
return null; return Optional.empty();
} }
} }
} }