将byte []转换为List <map <string,object =“”>&gt;

时间:2018-03-07 15:30:41

标签: arrays object type-conversion

我可以将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;
    }
}

2 个答案:

答案 0 :(得分:0)

根据documentation

  

任何读取超出相应writeObject方法写入的自定义数据边界的对象数据的尝试都将导致使用eof字段值为true抛出OptionalDataException。

所以你希望try { while(true) {并在catch (OptionalDataException e)时返回成功。

答案 1 :(得分:0)

我正在迭代ObjectInputStream并希望得到整个地图对象列表。 当我迭代ByteArrayInputStream时,我将整个byte[]转换为List<Map<String,Object>>

这是完整的方法:

private static List<Map<String, Object>> convertToObject(byte[] byteArr){
    List<Map<String, Object>> list = new ArrayList<>();
    Object obj = null;
    ByteArrayInputStream bis = null;
    ObjectInputStream ois = null;
    try {
        bis = new ByteArrayInputStream(byteArr);
        ois = new ObjectInputStream(bis);
        //this is the chage I did 
        while(bis.available() > 0){
            list.add((Map<String, Object>)ois.readObject());
        }
        //change complete
    } catch (IOException | ClassNotFoundException e) {
        e.printStackTrace();
    } 
    return  list;
}