Map对象如何转换为一个POJO对象呢?
下文笔者讲述Map对象转换为一个Pojo对象的方法及示例分享,如下所示
Map是我们日常开发中,经常使用的一个集合对象 Pojo是我们日常开发中的一个实体对象 那么如何将Map集合对象中 key ,value的形式转换为Pojo对象呢?
Map转pojo的实现思路
将Map对象转换为JSON对象
将JSON对象转换为pojo实体对象
使用以上操作,即可实现Map转POJO的效果
例:Map对象转POJO对象
package com.jd;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.springframework.http.converter.json.JsonbHttpMessageConverter;
import java.util.HashMap;
import java.util.Map;
/**
* java265.com map转换为 pojo对象
*
* */
public class MapToPoJo {
public static void main(String[] args) throws Exception {
Map<String, String> inputMap = new HashMap<>();
inputMap.put("name", "java265.com");
inputMap.put("email", "admin@java265.com");
ObjectMapper objectMapper = new ObjectMapper();
JsonConverter converter = new JsonConverter(objectMapper);
// Convert map to POJO
UserInfo user = converter.convertToPojo(inputMap,UserInfo.class);
System.out.println("user=======>:"+user);
}
}
class UserInfo {
public String name;
public String email;
@Override
public String toString() {
return "UserInfo{" +
"name='" + name + '\'' +
", email='" + email + '\'' +
'}';
}
}
class JsonConverter {
private final ObjectMapper objectMapper;
public JsonConverter(ObjectMapper objectMapper) {
this.objectMapper = objectMapper;
}
public <T> T convertToPojo(Map<String, String> flatMap, Class<T> clazz) throws Exception {
ObjectNode root = objectMapper.createObjectNode();
for (Map.Entry<String, String> entry : flatMap.entrySet()) {
setNestedValue(root, entry.getKey(), entry.getValue());
}
return objectMapper.treeToValue(root, clazz);
}
private void setNestedValue(ObjectNode node, String key, String value) {
String[] parts = key.split("\\.");
ObjectNode current = node;
for (int i = 0; i < parts.length - 1; i++) {
String part = parts[i];
if (part.matches(".*\\[\\d+\\]")) {
String arrayPart = part.replaceAll("\\[\\d+\\]", "");
int index = Integer.parseInt(part.replaceAll("[^\\d]", ""));
ArrayNode arrayNode = (ArrayNode) current.get(arrayPart);
if (arrayNode == null) {
arrayNode = current.putArray(arrayPart);
}
while (arrayNode.size() <= index) {
arrayNode.add(objectMapper.createObjectNode());
}
current = (ObjectNode) arrayNode.get(index);
} else {
ObjectNode child = (ObjectNode) current.get(part);
if (child == null) {
child = current.putObject(part);
}
current = child;
}
}
current.put(parts[parts.length - 1], value);
}
}
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。


