Home > Enterprise >  How do I deserialize a deconstructed List?
How do I deserialize a deconstructed List?

Time:03-30

I have a TreeMap I'm trying to make serializable, but instead of sending the entire object, I want to deconstruct it, send the data, and reconstruct at the other end. I serialize it with

for (Map.Entry<Integer, LinkedList<T>> entry: map.entrySet()) {
    s.writeObject("p" entry.getKey());

    for (T t : entry.getValue()) {
        s.writeObject(t);
    }
}

I will deserialize it with something like

LinkedList<T> list = new LinkedList<>();
int p = Integer.parseInt(((String) s.readObject()).substring(1));

while (s.available() != 0) {
    Object o = s.readObject();
    
    if (((String) o).charAt(0) == 'p') {
        store.put(p, new LinkedList<>(list));
        p = Integer.parseInt(((String) o).substring(1));
        list = new LinkedList<>();

    } else {
        list.add((T) o);
    }
}

The question I have is whether there is a better way to know when the object has finished sending than available being 0?

(Answers such as "Why are you doing it that way, just use default serialization" are not helpful.)

CodePudding user response:

The serialization format you're using doesn't have enough information to reconstruct the list -- e.g. if a T is a String starting with p.

Instead, first, serialize the number of entries in the map as an int. Then, that many times, serialize the key, and then entry.getValue().size(), and then the values.

That provides enough information at the other end to deserialize precisely the right amount.

  • Related