我需要将Map数组转换为包含memeber变量作为POJO数组的模型类,而无需遍历变量。例如如下:
foreach (string path in files) {
using (var ms = new MemoryStream()) //keep stream around
{
using (var fs = new FileStream(path, FileMode.Open)) // keep file around
{
// create and save bitmap to memorystream
using(var bmp = new Bitmap(fs))
{
bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
}
}
// write the PNG back to the same file from the memorystream
using(var png = Image.FromStream(ms))
{
png.Save(path);
}
}
}
模型类为:
Map<String,String>[] StudentArray= new HashMap[2];
Map<String,String> map1= new HashMap<String,String>();
map1.put("id","1");
map1.put("name","ABC");
Map<String,String> map2= new HashMap<String,String>();
map1.put("id","1");
map1.put("name","DEF");
StudentArray[0]=map1;
StudentArray[1]=map2;
我需要将地图数组转换为StudentArray模型POJO。
答案 0 :(得分:1)
Java 8中的流有助于实现内部迭代。 下面的代码将起作用。
List<Student> studentList = Arrays.stream(StudentArray).map(studentMap->
getStudentObject(studentMap)).collect(Collectors.toList());
这里,studentMap将作为StudentArray []的一个实例进行迭代,并且下面的方法会将这些实例中的每一个转换为Student POJO类,该类收集在List studentList中。
使用com.fasterxml.jackson.core:jackson-databind:2.7.3 jar来使用ObjectMapper的convertValue方法:
private Student getStudentObject(Map studentMap){
ObjectMapper m = new ObjectMapper(); // // jackson's objectmapper
return m.convertValue(studentMap, Student.class);
}