57 lines
1.4 KiB
Java
57 lines
1.4 KiB
Java
package helpers;
|
|
|
|
import java.util.Collection;
|
|
import java.util.List;
|
|
import java.util.stream.Collectors;
|
|
|
|
import org.apache.commons.lang3.StringUtils;
|
|
|
|
import com.fasterxml.jackson.core.JsonProcessingException;
|
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
|
import com.fasterxml.jackson.datatype.hibernate5.Hibernate5Module;
|
|
import com.fasterxml.jackson.datatype.hibernate5.Hibernate5Module.Feature;
|
|
|
|
|
|
public class SerializerProvider {
|
|
|
|
|
|
private static ObjectMapper objectMapper = null;
|
|
|
|
|
|
static {
|
|
initialize();
|
|
}
|
|
|
|
|
|
public static void initialize() {
|
|
Hibernate5Module module = new Hibernate5Module();
|
|
module.enable(Feature.SERIALIZE_IDENTIFIER_FOR_LAZY_NOT_LOADED_OBJECTS);
|
|
objectMapper = new ObjectMapper()
|
|
// .setSerializationInclusion(Include.NON_NULL)
|
|
// .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
|
|
.registerModule(new Hibernate5Module())
|
|
;
|
|
}
|
|
|
|
public static ObjectMapper getJsonSerializer() {
|
|
if(objectMapper==null)
|
|
initialize();
|
|
return objectMapper;
|
|
}
|
|
|
|
public static String toJson(Object obj) {
|
|
try {
|
|
return getJsonSerializer().writeValueAsString(obj);
|
|
}catch(JsonProcessingException ex) {
|
|
return "";
|
|
}
|
|
}
|
|
|
|
public static String toJson(Collection<?> coll) {
|
|
List<String> list = coll.parallelStream().map(obj -> toJson(obj)).collect(Collectors.toList());
|
|
return "["+StringUtils.join(list.toArray(), ",")+"]";
|
|
}
|
|
|
|
|
|
}
|