I've been using XStream and Jettison to provide a way to convert Java
objects to and from JSON to be handled on javascript AJAX clients.
Over time there's been alot of issues that have come up with using
XStream and JETTISON (the way that lists of objects are represented in
XStream JETTISON are completely non-intuitive for client-side
javascript to parse or produce).
I'm looking for another JSON library and GSON looks promising. I'm
running into an issue though with being able to serialize a JSON
object and deserialize it in GSON when that object is a concrete
Message subclass and I only know to expect an instanceof "Message".
For example this fails in GSON:
class MockMessage {
int val = 1;
}
class MockMessageOther extends MockMessage {
int otherVal = 1;
}
public static void main(String[] args) {
Gson gson = new Gson();
MockMessage mock1 = new MockMessage();
MockMessage mock2 = new MockMessage();
MockMessageOther mock3 = new MockMessageOther();
List<MockMessage> messages = new ArrayList<MockMessage>();
messages.add(mock1);
messages.add(mock2);
messages.add(mock3);
String jsonString = gson.toJson(messages);
//JSON list format is non-intuitive single element array with
class name fields
System.out.println(jsonString);
List gsonJSONUnmarshalledMessages = (List)gson.fromJson
(jsonString, List.class);
//This will print 3 messages unmarshalled
System.out.println("XStream format JSON Number of messages
unmarshalled: " + gsonJSONUnmarshalledMessages.size());
}
In the GSON FAQ it states:
"Collections Limitations
* Can serialize collection of arbitrary objects but can not
deserialize from it
o Because there is no way for the user to indicate the type
of the resulting object
* While deserializing, Collection must be of a specific generic
type
All of this makes sense, and is rarely a problem when following good
Java coding practices "
Is my generic messaging system breaking some "good Java coding
practices" and if so what other alternatives do I have for
implementing a system like this using GSON, I was able to get away
with it in XStream because type information is embedded in every
serialized object.
You can see a further discussion of XStream/Jettison and alternative
JSON to Java libraries on StackOverflow:
http://stackoverflow.com/questions/836805/in-xstream-is-there-a-better-way-to-marshall-unmarshall-listobjects-in-json-and