我正在尝试将 java bean 转换为 hashmap,然后将 hashmap 转换为 java bean。为了将 Java Object 转换为 hashmap,这篇文章帮助了我。 使用 commons-beans BeanUtils 将 JavaBean 转换为具有嵌套名称的键/值映射
下面的代码
public class Ax {
String axAttr;
public String getAxAttr() {
return axAttr;
}
public void setAxAttr(String axAttr) {
this.axAttr = axAttr;
}
List<Bx> bxs;
public List<Bx> getBxs() {
return bxs;
}
public void setBxs(List<Bx> bxs) {
this.bxs = bxs;
}
}
public class Bx {
String bxAttr;
public String getBxAttr() {
return bxAttr;
}
public void setBxAttr(String bxAttr) {
this.bxAttr = bxAttr;
}
List<Cx> cxs = new ArrayList<Cx>();
public List<Cx> getCxs() {
return cxs;
}
public void setCxs(List<Cx> cxs) {
this.cxs = cxs;
}
}
public class Cx {
String cxAttr;
public String getCxAttr() {
return cxAttr;
}
public void setCxAttr(String cxAttr) {
this.cxAttr = cxAttr;
}
List<String> items;
public List<String> getItems() {
return items;
}
public void setItems(List<String> items) {
this.items = items;
}
}
下面是存储在HashMap
axAttr --> axString bxs
[0].bxAttr --> bxString bxs
[0].cxs[0].cxAttr --> cxString bxs
[0].cxs[0].items[0] --> 一个
bxs[ 0].cxs[0].items[1] --> 两个
bxs[0].cxs[0].items[2] --> 三个
我将这些键值存储在DB
其中,稍后检索它们,并希望再次转换为 Java Bean。但是为了在我HashMap
的帮助下将其转换为 Java 对象propertyUtilsbean
NullPointerException.
这就是我执行的方式:
public static void main(String[] args) throws Exception {
Ax ax = new Ax();
ax.setAxAttr("axString");
Bx bx = new Bx();
bx.setBxAttr("bxString");
Cx cx = new Cx();
cx.setCxAttr("cxString");
List<Bx> bxs = new ArrayList<Bx>();
ax.setBxs(bxs);
ax.getBxs().add(bx);
List<Cx> cxs = new ArrayList<Cx>();
bx.setCxs(cxs);
bx.getCxs().add(cx);
List<String> xs = new ArrayList<String>();
cx.setAxs(xs);
cx.getAxs().add(new String("One"));
cx.getAxs().add(new String("Two"));
cx.getAxs().add(new String("Three"));
MyPropertyUtils myPropertyUtils = new MyPropertyUtils();
Map map = new HashMap();
for (String name : myPropertyUtils.listNestedPropertyName(ax)) {
map.put(name, PropertyUtils.getNestedProperty(ax, name));
}
Ax axNew = new Ax();
Set<Entry> set = map.entrySet();
for (Entry entry :set) {
BeanUtils.setProperty(axNew, entry.getKey().toString(), entry.getValue().toString());
}
}
例外
Exception in thread "main" java.lang.NullPointerException
at org.apache.commons.beanutils.PropertyUtilsBean.getIndexedProperty(PropertyUtilsBean.java:507)
at org.apache.commons.beanutils.PropertyUtilsBean.getIndexedProperty(PropertyUtilsBean.java:410)
at org.apache.commons.beanutils.PropertyUtilsBean.getNestedProperty(PropertyUtilsBean.java:768)
at org.apache.commons.beanutils.PropertyUtilsBean.getProperty(PropertyUtilsBean.java:846)
at org.apache.commons.beanutils.BeanUtilsBean.setProperty(BeanUtilsBean.java:903)
at org.apache.commons.beanutils.BeanUtils.setProperty(BeanUtils.java:456)
at com.wavecrest.aspect.Test1.main(Test1.java:57)
接受任何建议: