map转实体类
程序员文章站
2022-06-15 11:01:52
...
Entity entity = JacksonUtils.fromJson(map, Entity.class);
package com.sccl.common.utils;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;
import java.util.stream.Collectors;
import org.springframework.util.CollectionUtils;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.type.TypeFactory;
import com.sccl.common.collect.OptionalExt;
import lombok.extern.slf4j.Slf4j;
/**
* @author
* @date 2018-07-19
*/
@Slf4j
public class JacksonUtils {
private static ObjectMapper mapper;
private static ObjectMapper mapperWithNon;
static {
mapper = new ObjectMapper();
//Mon Sep 21 16:25:03 CST 2020
//Mon Sep 21 16:25:03 CST 2020
mapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY)
.setTimeZone(TimeZone.getTimeZone("GMT+8"))
.setDateFormat(new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
//保留空值
mapperWithNon = new ObjectMapper();
mapperWithNon.setTimeZone(TimeZone.getTimeZone("GMT+8"))
.setDateFormat(new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
mapperWithNon.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
mapperWithNon.getSerializerProvider().setNullValueSerializer(new JsonSerializer<Object>() {
@Override
public void serialize(Object arg0, JsonGenerator arg1, SerializerProvider arg2) throws IOException, JsonProcessingException {
arg1.writeString("");
}
});
}
public static String toJson(Object obj) {
try {
return mapper.writeValueAsString(obj);
} catch (IOException e) {
if (log.isErrorEnabled()) {
log.error("Convert bean to json exception. info:{}", e.getMessage());
}
}
return null;
}
public static String toJsonWithNullValue(Object obj) {
try {
return mapperWithNon.writeValueAsString(obj);
} catch (IOException e) {
if (log.isErrorEnabled()) {
log.error("Convert bean to json exception. info:{}", e.getMessage());
}
}
return null;
}
public static <T> T fromJson(String json, Class<T> clazz) {
try {
return mapper.readValue(json, clazz);
} catch (IOException e) {
if (log.isErrorEnabled()) {
log.error("Convert json to bean through class template failed. info:{}", e.getMessage());
}
}
return null;
}
@SuppressWarnings("rawtypes")
public static <T> T fromJson(Map map, Class<T> clazz) {
return fromJson(toJson(map), clazz);
}
public static <T> T fromJson(String json, TypeReference<T> reference) {
try {
return mapper.readValue(json, reference);
} catch (IOException e) {
if (log.isErrorEnabled()) {
log.error("Convert json to bean through TypeReference failed. info:{}", e.getMessage());
}
}
return null;
}
/**
* json 字符串转list<T>
*
* @param json
* @param clazz
* @return List<T>
* @Title: toList
* @author: UFO
* @date: 2020年9月14日 下午3:43:20
* @throws:
*/
public static <T> List<T> toList(String json, Class<T> clazz) {
TypeFactory typeFactory = mapper.getTypeFactory();
List<T> list = null;
try {
list = mapper.readValue(json, typeFactory.constructCollectionType(List.class, clazz));
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return list;
}
public static <T> List<T> toList(String json, TypeReference<List<T>> reference) {
List<T> list = null;
try {
list = mapper.readValue(json, reference);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return list;
}
/**
* 对象转Map
*
* @param obj 对象
* @param <T>
* @return map
*/
public static <T> Map<String, Object> toMap(T obj) {
Map<String, Object> map = new LinkedHashMap<>();
Class<?> clazz = obj.getClass();
try {
for (Field field : clazz.getDeclaredFields()) {
field.setAccessible(true);
String fieldName = field.getName();
map.put(fieldName, OptionalExt.ofNullable(field.get(obj)).orElse(""));
}
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return map;
}
public static <T> List<Map<String, Object>> toMap(List<T> obj) {
if (CollectionUtils.isEmpty(obj)) {
return null;
}
return obj.stream()
.map(JacksonUtils::toMap)
.collect(Collectors.toList());
}
/**
* Map转对象
*
* @param map
* @param clazz 类模板
* @param <T>
* @return 对象
*/
public static <T> T fromMap(Map<String, Object> map, Class<T> clazz) {
if (map == null) {
return null;
}
T obj = null;
try {
obj = clazz.newInstance();
Field[] fields = clazz.getDeclaredFields();
for (Field field : fields) {
int mod = field.getModifiers();
if (Modifier.isStatic(mod) || Modifier.isFinal(mod)) {
continue;
}
field.setAccessible(true);
if (map.containsKey(field.getName())) {
field.set(obj, map.get(field.getName()));
}
}
} catch (InstantiationException | IllegalAccessException e) {
e.printStackTrace();
}
return obj;
}
public static <T> List<T> fromMap(List<Map<String, Object>> map, Class<T> clazz) {
if (CollectionUtils.isEmpty(map)) {
return null;
}
return map.stream()
.map(item -> fromMap(item, clazz))
.collect(Collectors.toList());
}
public static void main(String[] args) {
/*String str = "{\"name\":\"test_name\",\"code\":\"test_code\",\"age\":20,\"data\":{\"sub\":\"test\",\"name\":\"tom\"}}";
@SuppressWarnings("unchecked")
Map<String, Object> obj = fromJson(str, Map.class);
@SuppressWarnings({"unchecked", "rawtypes"})
Map<String, Object> data = (Map) obj.get("data");
System.out.println(data);
str = "[{\"c1\":\"name\",\"field\":\"name\"},{\"c2\":\"code\",\"field\":\"code\"}]";
List<Map<String, Object>> list = toList(str, new TypeReference<List<Map<String, Object>>>() {
});
System.out.println(list);
System.out.println(list.get(1).get("field").toString());
str = "[{\"title\":\"序号\",\"type\":\"index\",\"align\":\"center\",\"width\":50,\"__id\":\"d5dzRn\"},{\"title\":\"类型\",\"key\":\"specName\",\"width\":80,\"__id\":\"qHngF3\"},{\"title\":\"名称\",\"key\":\"name\",\"__id\":\"kUN0Gj\"},{\"title\":\"编码\",\"key\":\"code\",\"__id\":\"6GBfWL\"},{\"title\":\"工程状态\",\"key\":\"projectStatusName\",\"width\":80,\"__id\":\"WWLPPK\"},{\"title\":\"项目管理员\",\"key\":\"managerName\",\"width\":80,\"__id\":\"b1UjWO\"},{\"title\":\"项目管理员联系电话\",\"key\":\"managerTel\",\"width\":120,\"__id\":\"HLSMaD\"},{\"title\":\"施工单位名称\",\"key\":\"constUnitName\",\"__id\":\"8MKkk3\"},{\"title\":\"施工单位联系电话\",\"key\":\"constUnitTel\",\"width\":120,\"__id\":\"flqI3B\"},{\"title\":\"验证状态\",\"key\":\"checkStatusName\",\"width\":80,\"__id\":\"pxA1jv\"},{\"title\":\"操作\",\"key\":\"action\",\"align\":\"center\",\"width\":100,\"__id\":\"1kpUSu\"}]";
list = toList(str, new TypeReference<List<Map<String, Object>>>() {
});
System.out.println(list);*/
Map<String, String> map=new HashMap<String, String>();
map.put("k1", "v1");
map.put("k2", "v2");
map.put("k3", "");
map.put("k4", null);
String str=toJsonWithNullValue(map);
System.out.println(str);
}
}