我正在寻找将整个pojo转换为Map<String,String>
的实用程序。
我到处都能看到示例,其中pojo转换为Map<String,Object>
。
但是我专门在寻找Map<String,String>
。
答案 0 :(得分:1)
在这里重要的是要了解POJO的关键和价值。您可以覆盖POJO的toString并将其用作值。
public class Main {
public static void main(String[] args) {
Map<String, String> result = new HashMap<>();
result.put("key1", new POJO("Done").toString());
result.put("key2", new POJO("Clarke").toString());
}
}
public class POJO {
private String name;
public POJO(String name) {
this.name = name;
}
@Override
public String toString() {
return name;
}
}
如果将字段名称用作键,则可以使用反射。请注意,如果将POJO中的field修饰符更改为private,则需要稍微更改代码。了解反射。
public class Main {
public static void main(String[] args) throws IllegalAccessException {
Map<String, String> result = new HashMap<>();
POJO pojo = new POJO("okGoogle", 12345);
Class classPOJO = pojo.getClass();
Field [] allFields = classPOJO.getFields();
for(Field field : allFields){
String key = field.getName();
String value = null;
if( field.get(pojo) != null){
value = field.get(pojo).toString();
}
result.put(key, value);
}
System.out.println(result.get("name"));
System.out.println(result.get("id"));
}
}
和 POJO 模型
public class POJO {
public String name;
public int id;
public POJO(String name, int id) {
this.name = name;
this.id = id;
}
}
答案 1 :(得分:0)
public class Main {
public static void main(String[] args) {
Person person = new Person();
person.setName("Abhishek");
person.setAge("30");
Person person1 = new Person();
person1.setName("Abhi");
person1.setAge("28");
Map<String, Map<String, String>> resultMap = new HashMap<>();
Map<String, String> result = new HashMap<>();
result.put("name", person.getName());
result.put("age", person.getAge());
resultMap.put("object1", result);
result = new HashMap<>();
result.put("name", person1.getName());
result.put("age", person1.getAge());
resultMap.put("object2", result);
}
}
public class Person {
private String name;
private String age
//setters and getters
}