added json module
All checks were successful
Build, test and publish the Quarkus libraries / build (push) Successful in 10m33s

This commit is contained in:
Jorge Bornhausen 2024-10-18 23:47:10 +02:00
parent 7d01a51fc8
commit 054aa67d34
6 changed files with 166 additions and 0 deletions

View file

@ -0,0 +1,13 @@
package ch.phoenixtechnologies.quarkus.commons.json;
import com.fasterxml.jackson.core.type.TypeReference;
public interface JsonService {
String toJson(Object object);
<T> T fromJson(String json, Class<T> clazz);
<T> T fromJson(String json, TypeReference<T> typeReference);
}

View file

@ -0,0 +1,48 @@
package ch.phoenixtechnologies.quarkus.commons.json;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.quarkus.arc.DefaultBean;
import jakarta.enterprise.context.ApplicationScoped;
@DefaultBean
@ApplicationScoped
class JsonServiceImpl implements JsonService {
private final ObjectMapper objectMapper;
JsonServiceImpl(ObjectMapper objectMapper) {
this.objectMapper = objectMapper;
}
@Override
public String toJson(Object object) {
try {
return objectMapper.writeValueAsString(object);
} catch (JsonProcessingException e) {
throw new IllegalArgumentException("Unable to write object as json String: " + object, e);
}
}
@Override
public <T> T fromJson(String json, Class<T> clazz) {
try {
return objectMapper.readValue(json, clazz);
} catch (JsonProcessingException e) {
throw new IllegalArgumentException("Unable to read object of class [" + clazz.getName()
+ "] from json String: " + json, e);
}
}
@Override
public <T> T fromJson(String json, TypeReference<T> typeReference) {
try {
return objectMapper.readValue(json, typeReference);
} catch (JsonProcessingException e) {
throw new IllegalArgumentException("Unable to read object of type [" + typeReference.getType().getTypeName()
+ "] from json String: " + json, e);
}
}
}