Clase para el manejo de JSON Json to Object Object To Json
<!-- https://mvnrepository.com/artifact/org.json/json -->
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20170516</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.9.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-annotations -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.9.1</version>
</dependency>
package com.moov.solutions.ribeits.utils;
import java.io.IOException;
import java.io.StringWriter;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.HashSet;
import java.util.Locale;
import java.util.Set;
import org.apache.commons.lang.StringUtils;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ser.FilterProvider;
import com.fasterxml.jackson.databind.ser.impl.SimpleBeanPropertyFilter;
import com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider;
import com.moov.solutions.ribeits.beans.BeanConfig;
import com.moov.solutions.ribeits.model.exception.UtilsException;
public class JSonUtils <T>{
Class clazz;
ObjectMapper mapper = new ObjectMapper();
DateFormat df = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
public JSonUtils(Class clazz) {
this.clazz = clazz;
mapper.setDateFormat(df);
}
public String beanToJSon(T bean) throws UtilsException{
try {
return mapper.writeValueAsString(bean);
} catch (JsonProcessingException e) {
throw new UtilsException("Error al convertir beanToJSon: " + e.getMessage());
}
}
public String beanToJSon(T bean, String datePattern) throws UtilsException{
try {
SimpleDateFormat dateFormat = new SimpleDateFormat(datePattern);
mapper.setDateFormat(dateFormat);
return mapper.writeValueAsString(bean);
} catch (JsonProcessingException e) {
throw new UtilsException("Error al convertir beanToJSon: " + e.getMessage());
}
}
public String beanToJSon(T bean, String... fieldsOnlyIncluye ) throws UtilsException{
try {
ObjectMapper mapper = new ObjectMapper();
FilterProvider fp = JSonUtils.printOnlyArray("BeanFilterName", fieldsOnlyIncluye);
return mapper.writer(fp).writeValueAsString(bean);
} catch (JsonProcessingException e) {
throw new UtilsException("Error al convertir beanToJSon: " + e.getMessage());
}
}
public String beanToJSon(T bean, String datePattern, String... fieldsOnlyIncluye ) throws UtilsException{
try {
SimpleDateFormat dateFormat = new SimpleDateFormat(datePattern);
mapper.setDateFormat(dateFormat);
FilterProvider fp = JSonUtils.printOnlyArray("BeanFilterName", fieldsOnlyIncluye);
return mapper.writer(fp).writeValueAsString(bean);
} catch (JsonProcessingException e) {
throw new UtilsException("Error al convertir beanToJSon: " + e.getMessage());
}
}
public String beanToJSonSpecific(T bean,String fieldsToJson) throws UtilsException{
StringWriter writer = new StringWriter();
try {
JsonGenerator generator = new JsonFactory().createGenerator(writer);
String[] fields = StringUtils.split(fieldsToJson, ',');
generator.writeStartObject();
for (int i = 0; i < fields.length; i++) {
writeField(generator,fields[i],bean);
}
generator.writeEndObject();
generator.close();
return writer.toString();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
return "";
}
/*
* DATE FORMAT
* @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd/MM/yyyy HH:mm:ss")
* private Date date;
*/
public T JsonToBean(String json) throws UtilsException{
try {
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
return (T) mapper.readValue(json, clazz);
} catch (JsonProcessingException e) {
throw new UtilsException("Error al convertir beanToJSon: " + e.getMessage());
} catch (IOException e) {
throw new UtilsException("Error al convertir beanToJSon: " + e.getMessage());
}
}
private void writeField(final JsonGenerator g, final String fieldName, T bean) throws IOException {
Field field;
try {
field = clazz.getDeclaredField(fieldName);
Annotation annotation = field.getAnnotation(BeanConfig.class);
if (annotation != null) {
field.setAccessible(true);
BeanConfig beanConfig = (BeanConfig) annotation;
Object value = field.get(bean);
if (beanConfig.classType() == String.class) {
if (value != null) {
g.writeStringField(fieldName, (String) value);
} else {
g.writeStringField(fieldName, "");
}
}
if (beanConfig.classType() == Integer.class) {
if (value != null) {
g.writeNumberField(fieldName, ((Integer) value).intValue());
}else{
g.writeNumberField(fieldName, 0);
}
}
if (beanConfig.classType() == Double.class) {
if (value != null) {
g.writeNumberField(fieldName, (Double) value);
} else {
g.writeNumberField(fieldName, 0.0);
}
}
if (beanConfig.classType() == Float.class) {
if (value != null) {
g.writeNumberField(fieldName, (Float) value);
} else {
g.writeNumberField(fieldName, 0.0);
}
}
if (beanConfig.classType() == Boolean.class) {
if (value != null) {
g.writeBooleanField(fieldName, (Boolean) value);
} else {
g.writeBooleanField(fieldName, false);
}
}
if (beanConfig.classType() == Date.class) {
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss",new Locale("ES", "MX"));
if (value != null) {
g.writeStringField(fieldName, dateFormat.format((Date)value));
} else {
g.writeStringField(fieldName, "");
}
}
}
} catch (NoSuchFieldException | SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static FilterProvider printOnlyArray(String filterName,String... values ){
Set<String> printOnlyArray = new HashSet<String>(Arrays.asList(values));
SimpleBeanPropertyFilter filter = SimpleBeanPropertyFilter.serializeAll(printOnlyArray);
FilterProvider fp = new SimpleFilterProvider().addFilter(filterName, filter);
return fp;
}
public static FilterProvider excludeArray(String filterName,String... values ){
Set<String> excludeArray = new HashSet<String>(Arrays.asList(values));
SimpleBeanPropertyFilter filter = SimpleBeanPropertyFilter.serializeAllExcept(excludeArray);
FilterProvider fp = new SimpleFilterProvider().addFilter(filterName, filter);
return fp;
}
}
package omr.api.json;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ser.FilterProvider;
import com.fasterxml.jackson.databind.ser.impl.SimpleBeanPropertyFilter;
import com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider;
import omr.api.exception.JSONException;
public class JSONUtils<T> {
T t;
public JSONUtils(T t) {
this.t = t;
}
public String beanToJSON(Object bean) throws JSONException {
String strJson = "";
ObjectMapper mapper = new ObjectMapper();
try {
strJson = mapper.writeValueAsString(bean);
} catch (JsonProcessingException e) {
throw new JSONException("Error beanToSTring: " + e.getMessage());
}
return strJson;
}
public String beanToJSONFilterExclude(Object bean,String... filterFields) throws JSONException {
String strJson = "";
FilterProvider filterProvider = excludeArray("beanToJSONFilter", filterFields);
ObjectMapper mapper = new ObjectMapper();
try {
strJson = mapper.writer(filterProvider).writeValueAsString(bean);
} catch (JsonProcessingException e) {
throw new JSONException("Error beanToSTring: " + e.getMessage());
}
return strJson;
}
public T JSONToBean(String strJson, Class<T> clazz) throws JSONException {
T bean;
ObjectMapper mapper = new ObjectMapper();
try {
bean = mapper.readValue(strJson,clazz);
} catch (JsonProcessingException e) {
throw new JSONException("Error JSONToBean JsonProcessingException: " + e.getMessage());
} catch (IOException e) {
throw new JSONException("Error JSONToBean IOException: " + e.getMessage());
}
return bean;
}
public static FilterProvider excludeArray(String filterName,String... values ){
Set<String> excludeArray = new HashSet<String>(Arrays.asList(values));
SimpleBeanPropertyFilter filter = SimpleBeanPropertyFilter.serializeAllExcept(excludeArray);
FilterProvider fp = new SimpleFilterProvider().addFilter(filterName, filter);
return fp;
}
}