All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.github.naviit.libs.common.util.JsonUtil Maven / Gradle / Ivy

There is a newer version: 1.0.3
Show newest version
/************************************************************************
 * 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 keyExtractor) {
		Map map = new ConcurrentHashMap<>();
		return t -> map.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
	}

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy