com.feingto.iot.server.serialize.JSON Maven / Gradle / Ivy
package com.feingto.iot.server.serialize;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.fasterxml.jackson.databind.ser.FilterProvider;
import com.fasterxml.jackson.databind.ser.impl.SimpleBeanPropertyFilter;
import com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider;
import lombok.SneakyThrows;
import org.apache.commons.lang3.StringUtils;
import java.io.InputStream;
import java.util.*;
import java.util.stream.Collectors;
/**
* json字符串、对象、List转换工具类
*
* @author longfei
*/
@SuppressWarnings("unchecked")
public class JSON {
private static JSON instance;
private JSONObjectMapper objectMapper = new JSONObjectMapper();
public static JSON getInstance() {
if (null == instance) {
instance = new JSON();
}
return instance;
}
public JSON objectMapper(JSONObjectMapper objectMapper) {
this.objectMapper = objectMapper;
return this;
}
/**
* 过滤属性,配置@JsonFilter(filterName)使用
*/
public JSON filter(String filterName, String... properties) {
FilterProvider filterProvider = new SimpleFilterProvider().addFilter(filterName,
SimpleBeanPropertyFilter.serializeAllExcept(properties));
objectMapper.setFilterProvider(filterProvider);
return this;
}
public ObjectNode JSONObject() {
return objectMapper.createObjectNode();
}
public ArrayNode JSONArray() {
return objectMapper.createArrayNode();
}
@SneakyThrows
public JsonNode read(String json) {
return StringUtils.isNotBlank(json) ? objectMapper.readTree(json) : JSONObject();
}
/**
* byte[] read to JsonNode
*/
@SneakyThrows
public JsonNode read(byte[] bytes) {
return objectMapper.readTree(bytes);
}
/**
* inputStream read to JsonNode
*/
@SneakyThrows
public JsonNode read(InputStream inputStream) {
return objectMapper.readTree(inputStream);
}
/**
* pojo convert to json string
*/
@SneakyThrows
public String obj2json(Object pojo) {
return pojo != null ? objectMapper.writeValueAsString(pojo) : "";
}
/**
* json string convert to javaBean
*/
@SneakyThrows
public T json2pojo(String json, Class clazz) {
return StringUtils.isNotBlank(json) ? objectMapper.readValue(json, clazz) : null;
}
/**
* json string convert to map with javaBean
*/
public Map json2map(String json, Class clazz)
throws Exception {
Map> map = objectMapper.readValue(json,
new TypeReference
© 2015 - 2025 Weber Informatics LLC | Privacy Policy