io.luchta.forma4j.databind.convert.JsonDeserializer Maven / Gradle / Ivy
package io.luchta.forma4j.databind.convert;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.luchta.forma4j.databind.json.JsonNode;
import io.luchta.forma4j.databind.json.JsonNodes;
import io.luchta.forma4j.databind.json.JsonObject;
public class JsonDeserializer {
public JsonObject deserializeFromJson(String json) throws JsonMappingException, JsonProcessingException {
TypeReference> reference = new TypeReference>() {};
ObjectMapper mapper = new ObjectMapper();
Map map = mapper.readValue(json, reference);
return this.deserializeFromMap(map);
}
public JsonObject deserializeFromMap(Map map) {
JsonNode jsonNode = new JsonNode();
for (Map.Entry entry : map.entrySet()) {
jsonNode.putVar(entry.getKey(), this.interfiling(entry.getValue()));
}
return new JsonObject(jsonNode);
}
public JsonObject deserializeFromList(List list) {
List jsonObjects = new ArrayList<>();
JsonNodes jsonNodes = new JsonNodes();
for (T t : list) {
jsonObjects.add(this.interfiling(t));
}
return new JsonObject(jsonObjects);
}
private JsonObject interfiling(Object object) {
if (object instanceof Map) {
return this.deserializeFromMap((Map) object);
}
if (object instanceof List) {
return this.deserializeFromList((List) object);
}
return new JsonObject(object.toString());
}
}