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

chaschev.json.JacksonMapper Maven / Gradle / Ivy

package chaschev.json;

import chaschev.util.Exceptions;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectReader;
import com.fasterxml.jackson.databind.ObjectWriter;

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

/**
* @author Andrey Chaschev [email protected]
*/
public class JacksonMapper implements Mapper {
    public static final TypeReference> MAP_TYPE_REF = new TypeReference>() {};
    public static final TypeReference> STRING_MAP_TYPE_REF = new TypeReference>() {};

    protected final ObjectMapper mapper = new ObjectMapper();
    protected ObjectWriter writer = mapper.writer();

    @Override
    public JacksonMapper prettyPrint(boolean b){
        writer = b ? mapper.writerWithDefaultPrettyPrinter() : mapper.writer();
        return this;
    }

    @Override
    public String toJSON(Object obj) {
        try {
            return writer.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            throw Exceptions.runtime(e);
        }
    }

    @Override
    public  T fromJSON(String s, Class aClass) {
        try {
            final ObjectReader reader = mapper.reader(aClass);

            return reader.readValue(s);
        } catch (IOException e) {
            throw Exceptions.runtime(e);
        }
    }

    public Map toMap(String json){
        try {
            return mapper.readValue(json, MAP_TYPE_REF);
        } catch (IOException e) {
            throw Exceptions.runtime(e);
        }
    }

    public Map toStringMap(String json){
        try {
            return mapper.readValue(json, STRING_MAP_TYPE_REF);
        } catch (IOException e) {
            throw Exceptions.runtime(e);
        }
    }

//    public String toJson(Map map){
//        try {
//            writer.
//        } catch (IOException e) {
//            throw Exceptions.runtime(e);
//        }
//    }

    public ObjectMapper getMapper() {
        return mapper;
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy