This week's book giveaway is in the Java in General forum.
We're giving away four copies of Think Java: How to Think Like a Computer Scientist and have Allen B. Downey & Chris Mayfield on-line!
See this thread for details.
Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

XStream dynamically aliase on Set not working

 
George Yee
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am trying to dynamically alias object during XML serialization using XStream, here is the utility code:



Weh I pass a Set of int


What I got is
<set>
<int>1</int>
<int>2</int>
</set>

instead of(expected)
<EmpId>
<int>1</int>
<int>2</int>
</EmpId>

If I change this line
xStream.alias(alias, obj.getClass());
to
xStream.alias(alias, Set.class);

Then it works as expected.

Question:
How can dynamically assign alias by object class type?

George
 
g tsuji
Ranch Hand
Posts: 656
3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Due to XStream's use of its registry of Converters, you've sometime need to know exactly how it behaves, namely, what class to put as the 2nd arugment in the alias method. This, I think, is arguably troublesome...

In order to make serialization always responsive to an object's getClass()'s response as the proper 2nd argument to the alias method, the idea-conductor is to subclass the ClassAliasingMapper. It can be condensed into the set up of the instantiation of the XStream (as shown) and this is how. (I call the subclass SelfDoc... for the responsiveness to .getClass() always, hence, do not need a priori accepting the behaviour of default converters... you may sure call it anything you like.)

You might have to change this to that according to the exact outcome your like better (such as getSimpleName() here, to getName() or getCanonicalName() etc etc..., choose what you feel more comfortable.)
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic