简体   繁体   English

你能转换一个Java Map吗? <Long,CustomObject> 到byte []然后回到Map <Long,CustomObject> ?

[英]Can you convert a Java Map<Long,CustomObject> to byte[] then back to Map<Long,CustomObject>?

I have the following: 我有以下内容:

public class CustomObject{
   public String name = "John";
   public int age = 14;
}

I have multiple CustomObject that are stored in a map into this variable: 我有多个CustomObject存储在这个变量的映射中:

Map<Long, CustomObject> myCustomObjectsMap;

Is there a way for me to have two methods, one that converts this map into a byte array, and the other that just reads the bytearray and converts it back to Map myCustomObjectsMap? 有没有办法让我有两个方法,一个将此映射转换为字节数组,另一个只读取bytearray并将其转换回Map myCustomObjectsMap?

Yes you can. 是的你可以。

How's this? 这个怎么样?

public class ConvertMapToBytes {

    public static void main(String[] args) {
        Map<Long, CustomObject> map = new HashMap<Long, CustomObject>();

        CustomObject c = new CustomObject();
        c.age = 20;
        c.name = "name";

        CustomObject c2 = new CustomObject();

        map.put(1L, c);
        map.put(2L, c2);

        try {
            byte[] bytes = convertMap(map);

            System.out.println("got bytes");

            // deserialise
            Map<Long, CustomObject> map2 = convertBytes(bytes);
            for (CustomObject co : map2.values()) {
                System.out.println(co);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public static byte[] convertMap(Map<Long, CustomObject> map) throws Exception {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        new ObjectOutputStream(baos).writeObject(map);
        return baos.toByteArray();
    }

    @SuppressWarnings("unchecked")
    public static Map<Long, CustomObject> convertBytes(byte[] obj) throws Exception {
        return (Map<Long, CustomObject>)new ObjectInputStream(new ByteArrayInputStream(obj)).readObject();
    }

}

class CustomObject implements Serializable {
    private static final long serialVersionUID = 1L;

    public String name = "John";
    public int age = 14;

    @Override
    public String toString() {
        return "name: " + name + ", age: " + age;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM