Commit fc630c5e by Nepxion

增加JacksonSerializer

parent 75c6663b
...@@ -24,6 +24,7 @@ public class PluginConstant { ...@@ -24,6 +24,7 @@ public class PluginConstant {
public static final String RULE = "rule"; public static final String RULE = "rule";
public static final String REACH_MAX_LIMITED_COUNT = "reach max limited count"; public static final String REACH_MAX_LIMITED_COUNT = "reach max limited count";
public static final String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss.SSS";
public static final String ENCODING_UTF_8 = "UTF-8"; public static final String ENCODING_UTF_8 = "UTF-8";
public static final String SEPARATE = ";"; public static final String SEPARATE = ";";
} }
\ No newline at end of file
package com.nepxion.discovery.plugin.framework.serializer;
/**
* <p>Title: Nepxion Discovery</p>
* <p>Description: Nepxion Discovery</p>
* <p>Copyright: Copyright (c) 2017-2050</p>
* <p>Company: Nepxion</p>
* @author Haojun Ren
* @version 1.0
*/
import java.text.SimpleDateFormat;
import org.apache.commons.lang3.StringUtils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.nepxion.discovery.plugin.framework.constant.PluginConstant;
public class JacksonSerializer {
private ObjectMapper objectMapper;
public JacksonSerializer() {
objectMapper = new ObjectMapper();
objectMapper.setDateFormat(new SimpleDateFormat(PluginConstant.DATE_FORMAT));
}
public <T> 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 <T> T fromJson(String json, Class<T> 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 <T> T fromJson(String json, TypeReference<T> 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 ObjectMapper getObjectMapper() {
return objectMapper;
}
}
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment