com.github.naviit.libs.common.util.JsonUtil Maven / Gradle / Ivy
/************************************************************************
* Copyright 2017 by DTT - All rights reserved. *
************************************************************************/
package com.github.naviit.libs.common.util;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.function.Predicate;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
/**
* Author: Dang Thanh Tung
* Email: [email protected]
* Created: 09/07/2017
*/
public class JsonUtil {
private static final ObjectMapper MAPPER;
static {
MAPPER = new ObjectMapper();
MAPPER.setSerializationInclusion(Include.NON_NULL);
}
public static String toJson(O o) {
try {
return MAPPER.writeValueAsString(o);
} catch (Exception e) {
return e.getMessage();
}
}
public static T toObject(String jsonStr, final Class clazz) {
try {
return MAPPER.readValue(jsonStr, clazz);
} catch (Exception e) {
return null;
}
}
public static T toObject(String jsonStr, final TypeReference reference) {
try {
return MAPPER.readValue(jsonStr, reference);
} catch (Exception e) {
return null;
}
}
public static Predicate distinctByKey(Function super T, Object> keyExtractor) {
Map