io.github.kits.json.support.JacksonSupport Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of whimthen-kits Show documentation
Show all versions of whimthen-kits Show documentation
Easy to use java tool library.
The newest version!
package io.github.kits.json.support;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.type.CollectionType;
import com.fasterxml.jackson.datatype.jdk8.Jdk8Module;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.module.paramnames.ParameterNamesModule;
import io.github.kits.interfaces.JsonSupport;
import io.github.kits.log.Logger;
import java.io.IOException;
import java.util.List;
import java.util.Map;
/**
* @project: kits
* @created: with IDEA
* @author: nzlong
* @Date: 2019 01 24 10:00 | January. Thursday
*/
public class JacksonSupport implements JsonSupport {
public static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
static {
OBJECT_MAPPER.configure(JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true);
OBJECT_MAPPER
.registerModule(new ParameterNamesModule())
.registerModule(new Jdk8Module())
.registerModule(new JavaTimeModule());
OBJECT_MAPPER.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
OBJECT_MAPPER.configure(JsonGenerator.Feature.ESCAPE_NON_ASCII, false);
}
@Override
public String toJson(Object object) {
try {
if (object instanceof String) {
return object.toString();
}
return OBJECT_MAPPER.writeValueAsString(object);
} catch (JsonProcessingException e) {
Logger.error("Jackson writeValueAsString fail", e);
}
return null;
}
@Override
public T toObject(String jsonStr, Class clazz) {
T object = null;
try {
object = OBJECT_MAPPER.readValue(jsonStr, clazz);
} catch (IOException e) {
Logger.error("Jackson readValue fail", e);
}
return object;
}
@Override
public List toList(String jsonStr, Class clazz) {
List object = null;
try {
CollectionType javaType = OBJECT_MAPPER.getTypeFactory()
.constructCollectionType(List.class, clazz);
object = OBJECT_MAPPER.readValue(jsonStr, javaType);
} catch (IOException e) {
Logger.error("Jackson readValue fail", e);
}
return object;
}
@Override
public String prettyJson(Object object) {
try {
if (object instanceof String || object instanceof Character) {
try {
object = toObject(object.toString(), (Class) Map.class);
} catch (Throwable throwable) {
}
}
return OBJECT_MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(object);
} catch (Exception e) {
Logger.error("Jackson prettyJson fail", e);
}
return null;
}
}