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

com.nepxion.discovery.common.util.JsonUtil Maven / Gradle / Ivy

Go to download

Nepxion Discovery is a solution for Spring Cloud with blue green, gray, weight, limitation, circuit breaker, degrade, isolation, monitor, tracing, dye, failover, async agent

There is a newer version: 6.22.0
Show newest version
package com.nepxion.discovery.common.util;

/**
 * 

Title: Nepxion Discovery

*

Description: Nepxion Discovery

*

Copyright: Copyright (c) 2017-2050

*

Company: Nepxion

* @author Haojun Ren * @version 1.0 */ import java.io.IOException; import org.apache.commons.lang3.StringUtils; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializerProvider; import com.fasterxml.jackson.databind.ser.std.StdSerializer; public class JsonUtil { private static ObjectMapper objectMapper; static { objectMapper = new ObjectMapper(); // objectMapper.getSerializerProvider().setNullKeySerializer(new NullKeySerializer()); // objectMapper.setDateFormat(new SimpleDateFormat(DiscoveryConstant.DATE_FORMAT)); } public static class NullKeySerializer extends StdSerializer { private static final long serialVersionUID = -9176767187240330396L; public NullKeySerializer() { this(null); } public NullKeySerializer(Class object) { super(object); } @Override public void serialize(Object value, JsonGenerator gen, SerializerProvider provider) throws IOException { gen.writeFieldName(StringUtils.EMPTY); } } public static String toJson(T object) { if (object == null) { throw new IllegalArgumentException("Object is null"); } try { return objectMapper.writeValueAsString(object); } catch (JsonProcessingException e) { throw new IllegalArgumentException(e.getMessage(), e); } } public static T fromJson(String json, Class clazz) { if (StringUtils.isEmpty(json)) { throw new IllegalArgumentException("Json is null or empty"); } try { return objectMapper.readValue(json, clazz); } catch (Exception e) { throw new IllegalArgumentException(e.getMessage(), e); } } public static T fromJson(String json, TypeReference typeReference) { if (StringUtils.isEmpty(json)) { throw new IllegalArgumentException("Json is null or empty"); } try { return objectMapper.readValue(json, typeReference); } catch (Exception e) { throw new IllegalArgumentException(e.getMessage(), e); } } public static ObjectMapper getObjectMapper() { return objectMapper; } }