Results 1 to 12 of 12
  1. #1
    Zwander is offline Member
    Join Date
    Aug 2012
    Posts
    9
    Rep Power
    0

    Default Implementing Deserialization of Objects

    NOTE: this question was posted at stack overflow by me here.

    Say you have a bunch of animals, `Rat` `Cat` `Dog` and `Fish`, and you want to serialize/deserialize these animals. Each has its own `serialize()` method. That all works fine and good, if you want to save your Cat to a file, you call `Cat.serialize()` and then you write it to a file.

    But what about deserializing? Sure, you could save an extra bit of data that states the type of animal, then use reflection to get a static method (say, `deserialize(String serialized)`) and then invoke it. But that's not safe. What if someone creates a new animal 'Rabbit' and doesn't include a `deserialize(String serialized)` method? Sure, you could then just catch the error and ignore the issue, but that seems unclean and bad practice.

    You could also create an enum. Each item in the enum must have a `deserialize(String serialized)` method, and the aforementioned piece of data that states the type references the name of its enum item. Very clean. Problem is, not very adaptable. Enums don't allow for other animals to be added at runtime.

    The way I have been solving this issue is mapping the name of the objects against a deserializer object. Basically each animal would have to 'register' itself by entering it's name and deserializer (implements `Deserializer` interface) object into a HashMap. The deserializer object can then be retrieved via the name of the animal at a later time.

    My question is, what is the best method to go about implementing deserialization? Also, is the method I have been using good/bad practice?

    Finally, if you are wondering why animals would be added at runtime, the reason is because animals might be added by other non accessible parts of the program, or by things such as plugins.




    Example of the method I have been using is below.

    Animal Interface

    Java Code:
        public class Animal{
            public String serialize();
        }
    Deserializer Interface

    Java Code:
        public interface Deserializer{
            public Animal deserialize();
        }
    Deserializer Storer:

    Java Code:
        public class AnimalSpecies{
            public static final String DELIMITER="|";
    	    private static HashMap<String,GameModeType> species=new HashMap<String,GameModeType>();
            public static addSpecies(String speciesName,Deserializer deserializer){
                if (species.contains(speciesName)){
                    //Throw error
                }
                species.put(speciesName,deserializer);
            }
            public static Deserializer getSpeciesDeserializer(String speciesName){
                return species.get(speciesName);
            }
        }
    Cat class

    Java Code:
        public class Cat implements Animal{
            public static  final String DELIMITER=AnimalSpecies.DELIMITER;
            private String type;
            private int age;
            private String name;
            public static register(){
                AnimalSpecies.addSpecies("CAT",new deserializer());
            }
            public Cat(String name,String type,Int age){
                this.type=type;
                this.age=age;
                this.name=name;
            }
            public String serialize(){
                return "CAT"+DELIMITER+type+DELIMITER+age+DELIMITER+name;
            }
            private static class deserializer implements Deserializer{
                @Override
                public Cat deserialize(String serialized){
                    String[] split=serialized.split(DELIMITER);
                    return new Cat(split[3].split[1],Integer.parseInt(split[2]));
                }
            }
        }
    Then in you main method you would call:

    Cat.register();

    And when you needed to deserialize:

    Java Code:
            Deserializer d=AnimalSpecies.getSpeciesDeserializer(serialized.split(AnimalSpecies.DELIMITER)[0]);
            if (d!=null){
                d.deserialize(serialized);
            }
    After writing all this out, I cant help but notice how much my method requires cooperation/understanding from other parties. It cant be guaranteed that the correct delimiter will be used. What I mean by this is that any serialized Animal must have a way of identifying which animal it is so that it's deserializer can be accessed. This can be worked around by implementing a wrapper that adds this information directly before it is written to a file, and removes it directly before deserialization.




    Why not use built in serialization/deserialization?

    I would like the serialized data to be readable and easily editable.

  2. #2
    JosAH's Avatar
    JosAH is online now Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,538
    Blog Entries
    7
    Rep Power
    20

    Default Re: Implementing Deserialization of Objects

    Quote Originally Posted by Zwander View Post
    I would like the serialized data to be readable and easily editable.
    Doesn't the Externalizable interface solve your problem?

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  3. #3
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    12,016
    Rep Power
    20

    Default Re: Implementing Deserialization of Objects

    I'm quite confused.
    Why are you serialising them individually?

    What, exactly, are you trying to achieve?

    If you use ObjectInputStream to deserialise then you won't need to know what the Animal subclass is...you just need to give it to an Animal reference variable.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  4. #4
    Zwander is offline Member
    Join Date
    Aug 2012
    Posts
    9
    Rep Power
    0

    Default Re: Implementing Deserialization of Objects

    Quote Originally Posted by Tolls View Post
    I'm quite confused.
    Why are you serialising them individually?
    I dont understand what you are asking..? A bunch of these different types of animals may be serialized to one file.
    Quote Originally Posted by Tolls View Post
    I'm quite confused.
    What, exactly, are you trying to achieve?
    This is a theory question, not working code. The question is asking what the correct structure for this kind of deserialization is.

    Quote Originally Posted by Tolls View Post
    If you use ObjectInputStream to deserialise then you won't need to know what the Animal subclass is...you just need to give it to an Animal reference variable.
    Quote Originally Posted by Zwander View Post
    Why not use built in serialization/deserialization?
    I would like the serialized data to be readable and easily editable.


    Quote Originally Posted by JosAH View Post
    Doesn't the Externalizable interface solve your problem?
    I was unaware such a thing existed. After a brief look... It looks perfect! I'll do some tests and see if its what I need. Thank you C:

    EDIT:
    Here is the text file output from this test:
    http://www.byteslounge.com/tutorials...izable-example
    Implementing Deserialization of Objects-dfea50f591cd6e78469ae1475b661981.png
    Not exactly readable nor easily editable.

    See, the issue is, Externalizable still relies on ObjectOutputStream and ObjectInputStream which prints byte gobbledygook into text files.
    Last edited by Zwander; 07-16-2014 at 10:36 AM.

  5. #5
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    12,016
    Rep Power
    20

    Default Re: Implementing Deserialization of Objects

    Then use some form of JSON or XML (as suggested at SO).

    We use the Jackson FasterXML here at the moment, but there's loads of other packages that do the same sort of thing.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  6. #6
    gimbal2 is offline Just a guy
    Join Date
    Jun 2013
    Location
    Netherlands
    Posts
    4,030
    Rep Power
    6

    Default Re: Implementing Deserialization of Objects

    Yeah but Jackson is pretty much the most awesome ;) Especially if you combine it with JAXB.

    Although for basic JSON serialization/deserialization, nothing beats the simplicity of Google GSON IMO.
    "Syntactic sugar causes cancer of the semicolon." -- Alan Perlis

  7. #7
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    12,016
    Rep Power
    20

    Default Re: Implementing Deserialization of Objects

    Quote Originally Posted by gimbal2 View Post
    Yeah but Jackson is pretty much the most awesome ;) Especially if you combine it with JAXB.

    Although for basic JSON serialization/deserialization, nothing beats the simplicity of Google GSON IMO.
    We seem to be using FasterXML for the JSON stuff...no...don't ask me why.
    Tradition, I expect.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  8. #8
    gimbal2 is offline Just a guy
    Join Date
    Jun 2013
    Location
    Netherlands
    Posts
    4,030
    Rep Power
    6

    Default Re: Implementing Deserialization of Objects

    I suspect that the label "FasterXML", just like JAXB, stems from the time period where XML was the solution to all worldly problems.
    "Syntactic sugar causes cancer of the semicolon." -- Alan Perlis

  9. #9
    Zwander is offline Member
    Join Date
    Aug 2012
    Posts
    9
    Rep Power
    0

    Default Re: Implementing Deserialization of Objects

    I'd still like to know what the correct way of going about this is. I'm yet to use a library I don't absolutely have to use. Best way to learn IMO.

    This is more of a question of structure and theory, than looking for an easy solution.

    Looking at the way Externalizable 'does it's thing', it seems you include in the interface a deserialize(String serialized) method, then retrieve the class via its name (which is found in the serialized data). You then use reflection to access and call the deserialize(String serialized) method.
    Last edited by Zwander; 07-16-2014 at 01:07 PM. Reason: Fixed grammatical errors

  10. #10
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    12,016
    Rep Power
    20

    Default Re: Implementing Deserialization of Objects

    If you want readable output then use one the libraries that does that.
    (De)serialisation is all about transporting objects from one place to another, whether for messaging purposes or for persistence.
    It's not about producing a human readable output.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  11. #11
    JosAH's Avatar
    JosAH is online now Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,538
    Blog Entries
    7
    Rep Power
    20

    Default Re: Implementing Deserialization of Objects

    Also, Serialization is about a graph of objects, where the vertexes are the single objects and the edges are the references to (other) objects. It is not so trivial to implement that in a (free)text format ...

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  12. #12
    Zwander is offline Member
    Join Date
    Aug 2012
    Posts
    9
    Rep Power
    0

    Default Re: Implementing Deserialization of Objects

    Quote Originally Posted by Tolls View Post
    It's not about producing a human readable output.
    Yes I see your point. I am confusing configuration and serialization.

Similar Threads

  1. deserialization problem
    By urbanleg in forum Advanced Java
    Replies: 15
    Last Post: 08-08-2011, 10:56 AM
  2. Deserialization problems
    By rubikk in forum Advanced Java
    Replies: 16
    Last Post: 07-01-2011, 08:38 PM
  3. Replies: 3
    Last Post: 02-28-2011, 05:09 PM
  4. Problem Creating/implementing Objects
    By ramathews in forum New To Java
    Replies: 2
    Last Post: 02-25-2010, 03:42 AM
  5. Serialization/Deserialization Error
    By andrepezzo in forum Advanced Java
    Replies: 2
    Last Post: 12-16-2008, 05:36 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •