0

I have the following declaration of the static type Object:

Integer typeId;
//Obtaining typeId
Object containerObject = ContainerObjectFactory.create(typeId);

The factory can produce different types of container objects, e.g. Date, Integer, BigDecimal and so forth.

Now, after creating the containerObejct I need to serialize it to an object of type String and store it into a database with hibernate. I'm not going to provide Object-relational mapping because it doesn't relate to the question directly.

Well, what I want to do is to serialize the containerObject depending on it runtime-type and desirialize it later with the type it was serialized. Is it ever possible? Could I use xml-serialization for those sakes?

St.Antario
  • 26,175
  • 41
  • 130
  • 318
  • 2
    I would stay wary of serializing runtime types. It tends to bite you in ways you cannot imagine. After you accidentally rename the class or move it to another package, you encounter very nasty and hard-to-fix bugs. – Ilya Kogan Apr 11 '15 at 07:40
  • I think http://www.tutorialspoint.com/java/java_serialization.htm is appropriate here. – bgoldst Apr 11 '15 at 07:41
  • @bgoldst: he wants to serialise it as a string - so if he wants to use native Java serialisation, he'll have to (say) Base64 encode the result before persisting. – Greg Kopff Apr 11 '15 at 08:50

2 Answers2

3

There are numerous alternatives, and your question is quite broad. You could:

One key feature you mention is that the object type needs to be embedded in the serialised data. Native Java serialisation embeds the type in the data so this is a good candidate. This is a double-edged sword however, as this makes the data brittle - if at some time in the future you changed the fully qualified class name then you'd no longer be able to deserialise the object.

Gson, on the other hand, doesn't embed the type information, and so you'd have to store both the JSON and the object type in order to deserialise the object.

XML and JSON have advantages that they're a textual format, so even without deserialising it, you can use your human eyes to see what it is. Base64 encoded Java serialisation however, is an unintelligible blob of characters.

Greg Kopff
  • 15,945
  • 12
  • 55
  • 78
  • In fact, in the related column on the right is a link to the same question that you're asking, with similar answers to this: http://stackoverflow.com/questions/134492/how-to-serialize-an-object-into-a-string?rq=1 – Greg Kopff Apr 11 '15 at 09:12
  • It works perfectly. Thatnk you!! I'm sorry that I cannot upvote your post more than once. – St.Antario Apr 11 '15 at 11:32
0

There are multiple ways, but you need custom serialization scheme, e.g.:

D|25.01.2015
I|12345
BD|123456.123452436

where the first part of the String represents the type and the second part represents the data. You can even use some binary serialization scheme for this.

Crazyjavahacking
  • 9,343
  • 2
  • 31
  • 40