将嵌套属性键的Map<String, String>转换为POJO,可以通过以下步骤实现:
下面是一个示例代码:
import java.util.HashMap;
import java.util.Map;
public class MapToPOJOConverter {
public static void main(String[] args) {
Map<String, String> nestedMap = new HashMap<>();
nestedMap.put("person.name", "John");
nestedMap.put("person.age", "30");
nestedMap.put("person.address.city", "New York");
nestedMap.put("person.address.zip", "12345");
Person person = convertMapToPOJO(nestedMap);
System.out.println(person.getName()); // 输出:John
System.out.println(person.getAge()); // 输出:30
System.out.println(person.getAddress().getCity()); // 输出:New York
System.out.println(person.getAddress().getZip()); // 输出:12345
}
public static Person convertMapToPOJO(Map<String, String> nestedMap) {
Person person = new Person();
for (Map.Entry<String, String> entry : nestedMap.entrySet()) {
String[] keys = entry.getKey().split("\\.");
Map<String, Object> currentObject = person;
for (int i = 0; i < keys.length - 1; i++) {
if (!currentObject.containsKey(keys[i])) {
currentObject.put(keys[i], new HashMap<String, Object>());
}
currentObject = (Map<String, Object>) currentObject.get(keys[i]);
}
currentObject.put(keys[keys.length - 1], entry.getValue());
}
return person;
}
}
class Person {
private String name;
private int age;
private Address address;
// Getters and setters
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
}
class Address {
private String city;
private String zip;
// Getters and setters
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getZip() {
return zip;
}
public void setZip(String zip) {
this.zip = zip;
}
}
在上面的示例中,我们创建了一个嵌套属性的Map,然后使用convertMapToPOJO
方法将其转换为POJO对象。最终,我们可以通过POJO对象的属性访问嵌套的属性值。
腾讯云相关产品和产品介绍链接地址:
没有搜到相关的沙龙
领取专属 10元无门槛券
手把手带您无忧上云