package uulm.teamname.marvelous.gamelibrary.json; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.InjectableValues; import com.fasterxml.jackson.databind.ObjectMapper; 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. */ public class JSON { private final ObjectMapper mapper = new ObjectMapper(); public JSON (CharacterConfig config) { // add the config to the mappers InjectableValues, where it is later accessed by the EntityDeserializer this.mapper.setInjectableValues(new InjectableValues .Std() .addValue("CharacterConfig", config)); } /** Deserializes an incoming network message into a {@link EventMessage}. * @param input The JSON to deserialize * @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 Optional parse(String input) { try { return Optional.of(mapper.readValue(input, BasicMessage.class)); } catch (JsonProcessingException e) { e.printStackTrace(); return Optional.empty(); } } /** Serializes a {@link EventMessage} into a JSON string. * @param input The message to serialize * @return An {@link Optional}<{@link String}> of the message as JSON or * an empty {@link Optional} if the serialization failed */ public Optional stringify(BasicMessage input) { try { return Optional.of(mapper.writeValueAsString(input)); } catch (JsonProcessingException e) { e.printStackTrace(); return Optional.empty(); } } }