All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.jonnymatts.jzonbie.jackson.Deserializer Maven / Gradle / Ivy

package com.jonnymatts.jzonbie.jackson;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jonnymatts.jzonbie.Request;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import static java.util.stream.Collectors.toList;

public class Deserializer {

    private final ObjectMapper objectMapper;

    public Deserializer() {
        this.objectMapper = new JzonbieObjectMapper();
    }

    public Deserializer(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    public ObjectMapper getObjectMapper() {
        return objectMapper;
    }

    public  T deserialize(Request request, Class clazz) {
        return deserialize(request.getBody(), clazz);
    }

    public  T deserialize(String s, TypeReference typeReference) {
        try {
            return objectMapper.readValue(s, typeReference);
        } catch (IOException e) {
            throw new DeserializationException(String.format("Error deserializing %s", typeReference.getClass().getSimpleName()), e);
        }
    }

    public  T deserialize(String s, Class clazz) {
        try {
            return objectMapper.readValue(s, clazz);
        } catch (IOException e) {
            throw new DeserializationException(String.format("Error deserializing %s", clazz.getSimpleName()), e);
        }
    }

    public  T deserialize(Map map, Class clazz) {
        try {
            return objectMapper.convertValue(map, clazz);
        } catch (Exception e) {
            throw new DeserializationException(String.format("Error deserializing %s", clazz.getSimpleName()), e);
        }
    }


    public Map deserialize(String s) {
        if(s == null || s.isEmpty()) return null;

        try {
            return objectMapper.readValue(s, new TypeReference>() {});
        } catch (IOException e) {
            throw new DeserializationException("Error deserializing to map", e);
        }
    }

    public  List deserializeCollection(String s, Class clazz) {
        try {
            final List> maps = objectMapper.readValue(s, new TypeReference>() {});
            return maps.stream().map(t -> deserialize(t, clazz)).collect(toList());
        } catch (IOException e) {
            throw new DeserializationException("Error deserializing %s", e);
        }
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy