【发布时间】:2018-08-15 18:36:32
【问题描述】:
我可以将List<Map<String,Object>> 转换为byte[],
但是当我将byte[] 转换回List<Map<String,Object>> 时,它只给出第一个对象(键,值对)
如何遍历字节数组或 ObjectOutputStream?
但是,我尝试了 while (ObjectOutputStream#available() > 0 ) 但 ois.available() 返回 0
public class MyClass {
public static void main(String args[]) {
List<Map<String, Object>> list = new ArrayList<>();
Map<String, Object> map = new HashMap<>();
map.put("age", 12);
map.put("name","gh");
list.add(map);
Map<String, Object> map1 = new HashMap<>();
map1.put("age", 20);
map1.put("name","ty");
list.add(map1);
System.out.println(convertToObject(convertToByteArray(list)));
}
private static byte[] convertToByteArray(List<Map<String, Object>> resultSet) {
ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
try {
ObjectOutputStream out = new ObjectOutputStream(byteOut);
for (Map<String, Object> map : resultSet) {
out.writeObject(map);
}
} catch (IOException e) {
e.printStackTrace();
}
return byteOut.toByteArray();
}
private static Object convertToObject(byte[] byteArr){
Object obj = null;
ByteArrayInputStream bis = null;
ObjectInputStream ois = null;
try {
bis = new ByteArrayInputStream(byteArr);
ois = new ObjectInputStream(bis);
obj = ois.readObject();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
return obj;
}
}
【问题讨论】:
标签: arrays object type-conversion