Details
-
Type: Improvement
-
Status: Closed
-
Resolution: Won't Fix
-
Affects Version/s: None
-
Fix Version/s: None
-
Component/s: None
-
Labels:None
Description
It would be most excellent if two things were changed across the source:
1) Mapper had the following method added:
public String serializeObject(Object obj);
The default implementation would be:
public String serializeObject(Object obj)
{
if (obj == null)
return serializeClass(null);
else
return serializeClass(obj.getClass());
}
2. All the places where a converter is marshalling an object and it has an instance of the object being marshalled, call the object version instead of the class version. Eg: AbstractCollectionConverter.writeItem(...)
Instead of:
String name = mapper().serializedClass(item.getClass());
Replace with:
String name = mapper().serializedObject(item);
This would make it possible to write a Mapper wrapper which could return an alias based on values of the specific object instance instead of returning the same alias for all instances of the class.
As background, the reason I'm trying to do this is because I'm creating a custom extension of XStream which will load any unrecognised <elements> as a specific placeholder class (call it 'UnrecognisedObject'). This object has a Converter which will read and store all the XML contents of the reader and put it in UnrecognisedObject. This is working fine. The problem is that when I'm marshalling the object, if more than one element was unrecognised, XStream can only pick an alias at random from the ones it knows of for UnrecognisedObject.class.
I can't create custom classes on the fly without a lot of extra work and overhead, so the obvious route is to store the original element name in the UnrecognisedObject instance itself. Unfortuntately, there is no easy way to get this info back out of the object from within XStream. Thus, the proposal to modify the Mapper.
For the moment, my only route is to create a branch of XStream for this purpose. I would rather not do that and can supply my patches if they would be accepted...
Such an enhancement will violate the separation of concerns. A Mapper defines rules to name clases or fields based on types, but it does not deal with the objects itself. A Converter is responsible to render an object's value and can/should consider the rules of the mapper(s) to render its fields or contained elements (if any).
From your use case on the user's list I had until now only the impression, that you don't know elements at deserialization time, but you could not identify those while serializing them. It this is the case you may have a look at the CGLIBMapper andd CGLIBEnhancedConverter implementation. Further discussions about this please on the list.