workspace-task-executor-lib.../src/main/java/org/gcube/common/workspacetaskexecutor/JsonUtil.java

56 lines
1.3 KiB
Java

/**
*
*/
package org.gcube.common.workspacetaskexecutor;
import java.io.IOException;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
/**
* The Class JsonUtil.
*
* @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it
* Apr 26, 2018
* @param <T> the generic type
*/
public class JsonUtil<T> {
private ObjectMapper mapper = new ObjectMapper();
/**
* To json.
*
* @param obj the obj
* @return the string
* @throws JsonProcessingException the json processing exception
*/
public String toJSON(T obj) throws JsonProcessingException{
// Convert object to JSON string
return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(obj);
}
/**
* Read object.
*
* @param json the json
* @param obj the obj
* @return the t
* @throws JsonParseException the json parse exception
* @throws JsonMappingException the json mapping exception
* @throws IOException Signals that an I/O exception has occurred.
*/
public T readObject(String json, Class<T> obj) throws JsonParseException, JsonMappingException, IOException{
// Convert JSON string from file to Object
return mapper.readValue(json, obj);
}
}