json處理對象(Jackson)
import com.fasterxml.jackson.annotation.JsonInclude;import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import java.util.List;
import java.util.Map;
import java.util.Optional;
/**
* json util
*/
@Slf4j
public class JacksonUtils {
private static JsonGenerator jsonGenerator = null;
private static ObjectMapper objectMapper = null;
static {
if (objectMapper == null) {
objectMapper = new ObjectMapper();
}
//jsonGenerator = objectMapper.getFactory().createGenerator(outputStream, JsonEncoding.UTF8);
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
// objectMapper.setConfig(JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS,Boolean.TRUE);
// objectMapper.setConfig(JsonParser.Feature.ALLOW_BACKSLASH_ESCAPING_ANY_CHARACTER,Boolean.TRUE);
// objectMapper.setConfig(JsonParser.Feature.ALLOW_SINGLE_QUOTES,Boolean.TRUE);
// objectMapper.setConfig(JsonParser.Feature.ALLOW_NON_NUMERIC_NUMBERS,Boolean.TRUE);
}
public static Optional<String> obj2Str(Object obj){
try {
if (obj != null){
if (obj.getClass() == String.class){
return Optional.of(obj.toString());
}
return Optional.ofNullable(objectMapper.writeValueAsString(obj));
}
}catch (Exception e){
log.error(">>>>>>JacksonUtils obj2Str() Exception");
}
return Optional.empty();
}
public static <T> Optional<T> str2Bean(String json,Class<T> tClass){
try {
return Optional.ofNullable(objectMapper.readValue(json,tClass));
}catch (Exception e){
log.error(">>>>>>JacksonUtils str2Bean() Exception");
}
return Optional.empty();
}
public static <E> Optional<List<E>> str2List(String json, Class<E> tClass){
try {
return Optional.ofNullable(objectMapper.readValue(json,objectMapper.getTypeFactory().constructCollectionType(List.class,tClass)));
}catch (Exception e){
log.error(">>>>>>JacksonUtils str2List() Exception");
}
return Optional.empty();
}
public static <K,V> Optional<Map<K,V>> str2Map(String json, Class<K> kClass, Class<V> vClass){
try {
return Optional.ofNullable(objectMapper.readValue(json,objectMapper.getTypeFactory().constructMapType(Map.class,kClass,vClass)));
}catch (Exception e){
log.error(">>>>>>JacksonUtils str2Map() Exception");
}
return Optional.empty();
}
}
以上是 json處理對象(Jackson) 的全部内容, 来源链接: utcz.com/z/511797.html