Gamelib/src/main/java/uulm/teamname/marvelous/gamelibrary/json/JSON.java

51 lines
1.8 KiB
Java
Raw Normal View History

2021-04-29 14:45:18 +00:00
package uulm.teamname.marvelous.gamelibrary.json;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.InjectableValues;
import com.fasterxml.jackson.databind.ObjectMapper;
2021-06-03 01:46:58 +00:00
import uulm.teamname.marvelous.gamelibrary.config.CharacterConfig;
import uulm.teamname.marvelous.gamelibrary.messages.BasicMessage;
import uulm.teamname.marvelous.gamelibrary.messages.EventMessage;
/**
* Class that contains JSON encoding and decoding. It is initiated with the Character configuration.
*/
public class JSON {
2021-06-03 01:46:58 +00:00
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}.
2021-06-03 01:46:58 +00:00
* @param input The JSON to deserialize
* @return The parsed message or {@code null} if the deserialization failed
*/
public EventMessage parse(String input) {
EventMessage result = null;
try {
2021-06-03 01:46:58 +00:00
return mapper.readValue(input, EventMessage.class);
} catch (JsonProcessingException e) {
e.printStackTrace();
2021-06-03 01:46:58 +00:00
return null;
}
}
/** Serializes a {@link EventMessage} into a JSON string.
2021-06-03 01:46:58 +00:00
* @param input The message to serialize
* @return The message as JSON or {@code null} if the serialization failed
*/
2021-06-03 01:46:58 +00:00
public String stringify(BasicMessage input) {
try {
2021-06-03 01:46:58 +00:00
return mapper.writeValueAsString(input);
} catch (JsonProcessingException e) {
e.printStackTrace();
2021-06-03 01:46:58 +00:00
return null;
}
}
}