Hi Kay,
Kay Masslow wrote:
> Hi all,
>
> The FAQ recommends "implement a custom mapper to ignore unknown fields
> automatically (see acceptance test
> customMapperTest.testCanBeUsedToOmitUnexpectedElements())". However
> using this code seems to cause trouble with handling of collections.
You get trouble with *implicit* collections/arrays.
> Am I doing something wrong here?
Nothing, but the custom mapper interferes with the handling of the implicit
collection. The problem is, that those elements ("Item" in your case) are no
fields of Root. The reflection converter will now ask the mapper if it
should deserialize a field named "Item" and the custom mapper says no now,
because that field is not declared anywhere in the class hierarchy. If the
converter is told, not to deserialize this item, it stops .. and will not
look for a possible implicit element.
> Using XStream 1.4.4 Please see JUnit
> 4 code below: testFailsWithUnknownElements() notNull-Assertion fails
> because the List is not initialized.
This is another caveat of implicit collections (covered by FAQ): If no
element was found, the collection itself is not initialized i.e. the field
keeping the collection instance is null. Because of the "implicit"
declaration of the collection, XStream can no longer separate between an
empty collection and null, because the collection has no representation in
the XML at all. You may use a readResolve method to initialize it with an
empty collection (also FAQ).
It is possible to implement the custom mapper for implicit collections
though, but it costs a bit more runtime:
new MapperWrapper(next) {
public boolean shouldSerializeMember(Class definedIn, String fieldName) {
if (getImplicitCollectionDefForFieldName(definedIn, fieldName) != null)
{
return true;
}
return definedIn != Object.class ?
super.shouldSerializeMember(definedIn, fieldName) : false;
}
}
Cheers,
Jörg
---------------------------------------------------------------------
To unsubscribe from this list, please visit:
http://xircles.codehaus.org/manage_email