Reputation: 3857
I currently have this code I am trying to refactor in order to allow for more possible class types (simplified with dummy code, but the gist is the same):
private String serializeSomething(final SomeSpecificClass something) {
try {
return mapper.writeValueAsString(someething);
} catch (final IOException e) {
throw new SomeCustomException("blah", e);
}
}
private SomeSpecificClass deserializeSomething(final String payload) {
try {
return mapper.readValue(payload, SomeSpecificClass.class);
} catch (final IOException e) {
// do special things here
throw new SomeCustomException("blah", e);
}
}
We recently found out that we will probably have to accept other types here, not just SomeSpecificClass
. Is there a better way of doing this without having to change everything to Object
instead of SomeSpecificClass
? So that we can return the right type in deserializeSomething
(and not have to cast it after we get the return value from the caller)?
Upvotes: 2
Views: 1896
Reputation: 38655
Start from example implementation:
class JsonObjectConverter {
private ObjectMapper mapper = new ObjectMapper();
public String serialiseToJson(Object value) {
try {
return mapper.writeValueAsString(value);
} catch (JsonProcessingException e) {
throw new IllegalArgumentException("Could not serialise: " + value, e);
}
}
public <T> T deserialiseFromJson(String json, Class<T> clazz) {
try {
return mapper.readValue(json, clazz);
} catch (IOException e) {
throw new IllegalArgumentException("Could not deserialize: " + clazz, e);
}
}
public SomeSpecificClass deserialiseToSomeSpecificClass(String json) {
return deserialiseFromJson(json, SomeSpecificClass.class);
}
}
You can write two general methods: serialiseToJson
and deserialiseFromJson
which can serialise any type to JSON
and deserialise JSON
payload to given Class
. You can implement of course some extra methods for most common and most used classes like deserialiseToSomeSpecificClass
. You can write as many method as you need in this format: deserialiseToXYZ
.
Upvotes: 2