Hi,
Zdenko wrote:
> Jörg Schaible <Joerg.Schaible@...> writes:
>
>>
>> Hi,
>>
>> Zdenko wrote:
>>
>> >
>> > Hi Jörg,
>> > To clarify problem. Inner class deserialized using XStream is not
>> > initialized correctly. When I try to access outer class by referencing
>> > it: Outer.this
>> > I got null reference exception.
>> > While debugging I realized that instance of Inner class has this$1
>> > pointer of type Outer and it has value null.
>> > What should I do to get correctly initialized Inner class? (I have to
>> > access the instance of Outer class)
>>
>> When you marshal your object into XML, XStream will also marshal the
>> 'outer' instance and therefore restore both at unmarshalling. So how does
>> your object look like, how the XML representation and how do you
>> configure the XStream?
>>
>> - Jörg
>>
>
> I have XML which I do not control. XStream is used only for
> deserialization. I created simplified version of code I have, along with
> test.
>
> public class TestXmlDeserialization {
> /*
> <Outer UserId="SomeID">
> <Inner Name="InnerName">
> </Inner>
> </Outer>
> */
> @XStreamAlias("Outer")
> class Outer {
> @XStreamAlias("Inner") //Not needed, same happens when removed.
> class Inner {
> @XStreamAlias("Name")
> @XStreamAsAttribute
> String name;
> void doIt() {
> System.out.println(Outer.this);
> System.out.println(Outer.this.userId);
> }
> }
> @XStreamAlias("UserId")
> @XStreamAsAttribute
> String userId;
> @XStreamAlias("Inner")
> Inner inner;
> }
>
> public static void main(String[] args) {
>
> File fXmlFile = new File("c:\\temp\\inner.xml");
> try {
> XStream xstream = new XStream(new StaxDriver());
> xstream.processAnnotations(new Class[] {Outer.class});
> Object pojo = xstream.fromXML(fXmlFile);
> if(pojo instanceof Outer) {
> Outer ou = (Outer) pojo;
> ou.inner.doIt();
> }
> } catch (Exception e) {
> e.printStackTrace();
> }
> }
> }
>
> Output:
> null
> java.lang.NullPointerException
> at
> TestXmlDeserialization$Outer$Inner.doIt(TestXmlDeserialization.java:144)
> at TestXmlDeserialization.main(TestXmlDeserialization.java:164)
>
> I created Inner as inner class (not static inner) since I have to access
> instance of outer.
> From Inner class read attribute UserId of Outer class.
Sorry, but this is not how it works. XStream is from Java to XML and back.
Please serialize your object to XML and you'll see, what kind of XML XStream
actually expects. You can tweak the unmarshalling process, but it has its
limits. Your XML does not contain any reference from the "Inner" element to
the "Outer" element. There is no way to configure XStream to add this
relationship automatically at deserialization time, it must be present in
the XML.
- Jörg
---------------------------------------------------------------------
To unsubscribe from this list, please visit:
http://xircles.codehaus.org/manage_email