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 jdk.jshell.spi.ExecutionControl; import uulm.teamname.marvelous.gamelibrary.json.basic.BasicMessage; import uulm.teamname.marvelous.gamelibrary.json.basic.EventMessage; import uulm.teamname.marvelous.gamelibrary.json.config.CharacterConfig; /** * Class that contains JSON encoding and decoding. It is initiated with the Character configuration. */ public class JSON { private final ObjectMapper mapper; public JSON (CharacterConfig config) { this.mapper = new ObjectMapper(); // 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 The parsed message. */ public EventMessage parse(String input) { EventMessage result = null; try { result = mapper.readValue(input, EventMessage.class); } catch (JsonProcessingException e) { e.printStackTrace(); } return result; } /** Serializes a {@link EventMessage} into a JSON string. * @param input The message to serialize. * @return The message as JSON. */ public String stringify(BasicMessage input) throws ExecutionControl.NotImplementedException { String result = null; try { result = mapper.writeValueAsString(input); } catch (JsonProcessingException e) { e.printStackTrace(); } return result; } }