Skip field during deserialization

View: New views
20 Messages — Rating Filter:   Alert me  
< Prev | 1 - 2 | Next >

Skip field during deserialization

by Trumbo, Derek :: Rate this Message:

Reply to Author | View Threaded | Show Only this Message

Some parts of this message have been removed. Learn more about Nabble's security policy.
I am attempting to write some code that could avoid certain errors when deserializing an XML file that was generated a long time ago.  If I had a class with two fields:
 
class SerializationResult :
    SerializationMetadata metadata
    Object targetObject  -- holds actual content to be serialized to file
 
that serializes to (using toXML):
 
<SerializationResult>
  <metadata>
    <appName>testp</appName>
    <appVersion>1.0.0</appVersion>
    ...
  </metadata>
  <targetObject class="string">abcdef</targetObject>
</SerializationResult>
 
(targetObject in reality could possibly be an enormous object prone to deserialization errors)
 
Is there a way to have the fromXML method just completely skip the targetObject element/field and not attempt to construct objects from it?
 
I realize there is an omitField method but that seems only to be for the serialization side of things.
 
This would allow me to inspect all the metadata of the object written to the disk before deciding whether I want to fully deserialize the targetObject field (possibly after having set up some appropriate aliases, etc. as well).
 
Thanks much!
 
~ Derek
 

Re: Skip field during deserialization

by Jörg Schaible-2 :: Rate this Message:

Reply to Author | View Threaded | Show Only this Message

Hi Derek,

Trumbo, Derek wrote:

> I am attempting to write some code that could avoid certain errors when
> deserializing an XML file that was generated a long time ago.  If I had a
> class with two fields:
>
> class SerializationResult :
>     SerializationMetadata metadata
>     Object targetObject  -- holds actual content to be serialized to file
>
> that serializes to (using toXML):
>
> <SerializationResult>
>   <metadata>
>     <appName>testp</appName>
>     <appVersion>1.0.0</appVersion>
>     ...
>   </metadata>
>   <targetObject class="string">abcdef</targetObject>
> </SerializationResult>
>
> (targetObject in reality could possibly be an enormous object prone to
> deserialization errors)
>
> Is there a way to have the fromXML method just completely skip the
> targetObject element/field and not attempt to construct objects from it?
>
> I realize there is an omitField method but that seems only to be for the
> serialization side of things.

It's also for deserialization.

> This would allow me to inspect all the metadata of the object written to
> the disk before deciding whether I want to fully deserialize the
> targetObject field (possibly after having set up some appropriate aliases,
> etc. as well).

- Jörg



---------------------------------------------------------------------
To unsubscribe from this list, please visit:

    http://xircles.codehaus.org/manage_email



RE: Re: Skip field during deserialization

by Trumbo, Derek :: Rate this Message:

Reply to Author | View Threaded | Show Only this Message

If omitField is also for deserialization, then I hope I am just doing something incorrectly.  I cannot get omitField to ignore a field upon deserialization.

Here is a test program which demonstrates my confusion:

public class XStreamOmitTest {
    public static void main(String[] args) {
        XStream xstream = new XStream();
        A a = new A();
        a.x = "field 1";
        a.y = "field 2";
        String xml = xstream.toXML(a);
        System.out.println(xml);
        xstream.omitField(A.class, "y");
        A a2 = (A) xstream.fromXML(xml);
        System.out.println(a2.x);   // prints "field 1"
        System.out.println(a2.y);   // prints "field 2" (instead of "null")
        // The field 'y' should be uninitialized if it's
        // being skipped on deserialization, correct?
    }

    public static class A {
        public String x;
        public String y;
    }
}


Thanks again for your help!


-----Original Message-----
From: news [mailto:news@...] On Behalf Of Jörg Schaible
Sent: Monday, September 28, 2009 2:41 PM
To: user@...
Subject: [xstream-user] Re: Skip field during deserialization

Hi Derek,

Trumbo, Derek wrote:

> I am attempting to write some code that could avoid certain errors
> when deserializing an XML file that was generated a long time ago.  If
> I had a class with two fields:
>
> class SerializationResult :
>     SerializationMetadata metadata
>     Object targetObject  -- holds actual content to be serialized to
> file
>
> that serializes to (using toXML):
>
> <SerializationResult>
>   <metadata>
>     <appName>testp</appName>
>     <appVersion>1.0.0</appVersion>
>     ...
>   </metadata>
>   <targetObject class="string">abcdef</targetObject>
> </SerializationResult>
>
> (targetObject in reality could possibly be an enormous object prone to
> deserialization errors)
>
> Is there a way to have the fromXML method just completely skip the
> targetObject element/field and not attempt to construct objects from it?
>
> I realize there is an omitField method but that seems only to be for
> the serialization side of things.

It's also for deserialization.

> This would allow me to inspect all the metadata of the object written
> to the disk before deciding whether I want to fully deserialize the
> targetObject field (possibly after having set up some appropriate
> aliases, etc. as well).

- Jörg



---------------------------------------------------------------------
To unsubscribe from this list, please visit:

    http://xircles.codehaus.org/manage_email





---------------------------------------------------------------------
To unsubscribe from this list, please visit:

    http://xircles.codehaus.org/manage_email



RE: Re: Skip field during deserialization

by Jörg Schaible-2 :: Rate this Message:

Reply to Author | View Threaded | Show Only this Message

Hi Derek,

Trumbo, Derek wrote at Montag, 28. September 2009 23:51:

> If omitField is also for deserialization, then I hope I am just doing
> something incorrectly.  I cannot get omitField to ignore a field upon
> deserialization.
>
> Here is a test program which demonstrates my confusion:
>
> public class XStreamOmitTest {
>     public static void main(String[] args) {
>         XStream xstream = new XStream();
>         A a = new A();
>         a.x = "field 1";
>         a.y = "field 2";
>         String xml = xstream.toXML(a);
>         System.out.println(xml);
>         xstream.omitField(A.class, "y");
>         A a2 = (A) xstream.fromXML(xml);
>         System.out.println(a2.x);   // prints "field 1"
>         System.out.println(a2.y);   // prints "field 2" (instead of
>         "null") // The field 'y' should be uninitialized if it's
>         // being skipped on deserialization, correct?
>     }
>
>     public static class A {
>         public String x;
>         public String y;
>     }
> }

I had a closer look and it turns out, that the omitField declaration only
helps to omit XML tags that have no equivalent in the deserialized object
(otherwise XStream would throw an exception). If the field exists, the
omitField declaration is not even checked. You may open a JIRA issue for
this.

The only workaround I can currently think of is a custom converter based on
the ReflectionConverter that uses a filter for the ReflectionProvider,
something along:

class OmittingReflectionProvider extends ReflectionProvider {
    public OmittingReflectionProvider(Mapper mapper, ReflectionProvider
reflectionProvider) {
        super(mapper, new FilteringReflectionProvider(reflectionProvider));
    })
    public boolean canConvert(Class type) {
        return type == SerializationResult.class;
    }

    private static class FilteringReflectionProvider extends
ReflectionProviderWrapper {

        public FilteringReflectionProvider(final ReflectionProvider
reflectionProvider) {
            super(reflectionProvider);
        }

        public void visitSerializableFields(final Object object, final
Visitor visitor) {
            wrapped.visitSerializableFields(object, new Visitor() {
                public void visit(String name, Class type, Class definedIn,
Object value) {
                    if (!name.equals("targetObject")) {
                        visitor.visit(name, type, definedIn, value);
                    }
                }
            });
        }
    }
}

xstream.registerConverter(new
OmittingReflectionConverter(xstream.getMapper(),
xstream.getReflectionProvider()));

- Jörg


---------------------------------------------------------------------
To unsubscribe from this list, please visit:

    http://xircles.codehaus.org/manage_email



RE: RE: Re: Skip field during deserialization

by Trumbo, Derek :: Rate this Message:

Reply to Author | View Threaded | Show Only this Message

Jörg,

Thank you very much for investigating my problem in-depth.  I appreciate you taking the time to come up with a work around as well - very nice of you.

I created a JIRA entry just to record the issue for the future, even if it is a low priority item.

Thanks much.

~ Derek



-----Original Message-----
From: news [mailto:news@...] On Behalf Of Jörg Schaible
Sent: Wednesday, September 30, 2009 3:22 AM
To: user@...
Subject: [xstream-user] RE: Re: Skip field during deserialization

Hi Derek,

Trumbo, Derek wrote at Montag, 28. September 2009 23:51:

> If omitField is also for deserialization, then I hope I am just doing
> something incorrectly.  I cannot get omitField to ignore a field upon
> deserialization.
>
> Here is a test program which demonstrates my confusion:
>
> public class XStreamOmitTest {
>     public static void main(String[] args) {
>         XStream xstream = new XStream();
>         A a = new A();
>         a.x = "field 1";
>         a.y = "field 2";
>         String xml = xstream.toXML(a);
>         System.out.println(xml);
>         xstream.omitField(A.class, "y");
>         A a2 = (A) xstream.fromXML(xml);
>         System.out.println(a2.x);   // prints "field 1"
>         System.out.println(a2.y);   // prints "field 2" (instead of
>         "null") // The field 'y' should be uninitialized if it's
>         // being skipped on deserialization, correct?
>     }
>
>     public static class A {
>         public String x;
>         public String y;
>     }
> }

I had a closer look and it turns out, that the omitField declaration only helps to omit XML tags that have no equivalent in the deserialized object (otherwise XStream would throw an exception). If the field exists, the omitField declaration is not even checked. You may open a JIRA issue for this.

The only workaround I can currently think of is a custom converter based on the ReflectionConverter that uses a filter for the ReflectionProvider, something along:

class OmittingReflectionProvider extends ReflectionProvider {
    public OmittingReflectionProvider(Mapper mapper, ReflectionProvider
reflectionProvider) {
        super(mapper, new FilteringReflectionProvider(reflectionProvider));
    })
    public boolean canConvert(Class type) {
        return type == SerializationResult.class;
    }

    private static class FilteringReflectionProvider extends ReflectionProviderWrapper {

        public FilteringReflectionProvider(final ReflectionProvider
reflectionProvider) {
            super(reflectionProvider);
        }

        public void visitSerializableFields(final Object object, final Visitor visitor) {
            wrapped.visitSerializableFields(object, new Visitor() {
                public void visit(String name, Class type, Class definedIn, Object value) {
                    if (!name.equals("targetObject")) {
                        visitor.visit(name, type, definedIn, value);
                    }
                }
            });
        }
    }
}

xstream.registerConverter(new
OmittingReflectionConverter(xstream.getMapper(),
xstream.getReflectionProvider()));

- Jörg


---------------------------------------------------------------------
To unsubscribe from this list, please visit:

    http://xircles.codehaus.org/manage_email





---------------------------------------------------------------------
To unsubscribe from this list, please visit:

    http://xircles.codehaus.org/manage_email



RE: RE: Re: Skip field during deserialization

by darniz :: Rate this Message:

Reply to Author | View Threaded | Show Only this Message

Is there any update on this.
This is a big issue since any extra element in the xml response will blow off your code.


Any update when this issue will be fixed.

thanks
darniz



Trumbo, Derek wrote:
Jörg,

Thank you very much for investigating my problem in-depth.  I appreciate you taking the time to come up with a work around as well - very nice of you.

I created a JIRA entry just to record the issue for the future, even if it is a low priority item.

Thanks much.

~ Derek



-----Original Message-----
From: news [mailto:news@ger.gmane.org] On Behalf Of Jörg Schaible
Sent: Wednesday, September 30, 2009 3:22 AM
To: user@xstream.codehaus.org
Subject: [xstream-user] RE: Re: Skip field during deserialization

Hi Derek,

Trumbo, Derek wrote at Montag, 28. September 2009 23:51:

> If omitField is also for deserialization, then I hope I am just doing
> something incorrectly.  I cannot get omitField to ignore a field upon
> deserialization.
>
> Here is a test program which demonstrates my confusion:
>
> public class XStreamOmitTest {
>     public static void main(String[] args) {
>         XStream xstream = new XStream();
>         A a = new A();
>         a.x = "field 1";
>         a.y = "field 2";
>         String xml = xstream.toXML(a);
>         System.out.println(xml);
>         xstream.omitField(A.class, "y");
>         A a2 = (A) xstream.fromXML(xml);
>         System.out.println(a2.x);   // prints "field 1"
>         System.out.println(a2.y);   // prints "field 2" (instead of
>         "null") // The field 'y' should be uninitialized if it's
>         // being skipped on deserialization, correct?
>     }
>
>     public static class A {
>         public String x;
>         public String y;
>     }
> }

I had a closer look and it turns out, that the omitField declaration only helps to omit XML tags that have no equivalent in the deserialized object (otherwise XStream would throw an exception). If the field exists, the omitField declaration is not even checked. You may open a JIRA issue for this.

The only workaround I can currently think of is a custom converter based on the ReflectionConverter that uses a filter for the ReflectionProvider, something along:

class OmittingReflectionProvider extends ReflectionProvider {
    public OmittingReflectionProvider(Mapper mapper, ReflectionProvider
reflectionProvider) {
        super(mapper, new FilteringReflectionProvider(reflectionProvider));
    })
    public boolean canConvert(Class type) {
        return type == SerializationResult.class;
    }

    private static class FilteringReflectionProvider extends ReflectionProviderWrapper {

        public FilteringReflectionProvider(final ReflectionProvider
reflectionProvider) {
            super(reflectionProvider);
        }

        public void visitSerializableFields(final Object object, final Visitor visitor) {
            wrapped.visitSerializableFields(object, new Visitor() {
                public void visit(String name, Class type, Class definedIn, Object value) {
                    if (!name.equals("targetObject")) {
                        visitor.visit(name, type, definedIn, value);
                    }
                }
            });
        }
    }
}

xstream.registerConverter(new
OmittingReflectionConverter(xstream.getMapper(),
xstream.getReflectionProvider()));

- Jörg


---------------------------------------------------------------------
To unsubscribe from this list, please visit:

    http://xircles.codehaus.org/manage_email





---------------------------------------------------------------------
To unsubscribe from this list, please visit:

    http://xircles.codehaus.org/manage_email


RE: RE: Re: Skip field during deserialization

by brco3837 :: Rate this Message:

Reply to Author | View Threaded | Show Only this Message

Some parts of this message have been removed. Learn more about Nabble's security policy.

I asked this question a while back and was pointed to a the CustomMapperTest for a solution, this is what he wrote:

"Have a look at the CustomMapperTest in XStream's acceptance tests. It contains such a solution. However it may have side effect on implicit collections - therefore it might not be the proper solution for you."

 

This is what I found:
    private static XStream xStream = new XStream() {

        protected MapperWrapper wrapMapper(MapperWrapper next) {

            return new MapperWrapper(next) {

                @SuppressWarnings("unchecked")

                public boolean shouldSerializeMember(Class definedIn, String fieldName) {

                    if (definedIn != Object.class) {

                        return super.shouldSerializeMember(definedIn, fieldName);

                    }

                    logger.warn("Ignoring the fieldName {} as it must be new.", fieldName);

                    return false;

                }

            };

        }

    };

 

So far I haven’t had any problems when declaring XStream this way...

 

-----Original Message-----
From: darniz [mailto:rnizamuddin@...]
Sent: Tuesday, October 20, 2009 5:48 PM
To: user@...
Subject: RE: RE: Re: [xstream-user] Skip field during deserialization

 

 

Is there any update on this.

This is a big issue since any extra element in the xml response will blow

off your code.

 

 

Any update when this issue will be fixed.

 

thanks

darniz

 

 

 

 

Trumbo, Derek wrote:

>

> Jörg,

>

> Thank you very much for investigating my problem in-depth.  I appreciate

> you taking the time to come up with a work around as well - very nice of

> you.

>

> I created a JIRA entry just to record the issue for the future, even if it

> is a low priority item.

>

> Thanks much.

>

> ~ Derek

>

>

>

> -----Original Message-----

> From: news [mailto:news@...] On Behalf Of Jörg Schaible

> Sent: Wednesday, September 30, 2009 3:22 AM

> To: user@...

> Subject: [xstream-user] RE: Re: Skip field during deserialization

>

> Hi Derek,

>

> Trumbo, Derek wrote at Montag, 28. September 2009 23:51:

>

>> If omitField is also for deserialization, then I hope I am just doing

>> something incorrectly.  I cannot get omitField to ignore a field upon

>> deserialization.

>>

>> Here is a test program which demonstrates my confusion:

>>

>> public class XStreamOmitTest {

>>     public static void main(String[] args) {

>>         XStream xstream = new XStream();

>>         A a = new A();

>>         a.x = "field 1";

>>         a.y = "field 2";

>>         String xml = xstream.toXML(a);

>>         System.out.println(xml);

>>         xstream.omitField(A.class, "y");

>>         A a2 = (A) xstream.fromXML(xml);

>>         System.out.println(a2.x);   // prints "field 1"

>>         System.out.println(a2.y);   // prints "field 2" (instead of

>>         "null") // The field 'y' should be uninitialized if it's

>>         // being skipped on deserialization, correct?

>>     }

>>

>>     public static class A {

>>         public String x;

>>         public String y;

>>     }

>> }

>

> I had a closer look and it turns out, that the omitField declaration only

> helps to omit XML tags that have no equivalent in the deserialized object

> (otherwise XStream would throw an exception). If the field exists, the

> omitField declaration is not even checked. You may open a JIRA issue for

> this.

>

> The only workaround I can currently think of is a custom converter based

> on the ReflectionConverter that uses a filter for the ReflectionProvider,

> something along:

>

> class OmittingReflectionProvider extends ReflectionProvider {

>     public OmittingReflectionProvider(Mapper mapper, ReflectionProvider

> reflectionProvider) {

>         super(mapper, new

> FilteringReflectionProvider(reflectionProvider));

>     })

>     public boolean canConvert(Class type) {

>         return type == SerializationResult.class;

>     }

>

>     private static class FilteringReflectionProvider extends

> ReflectionProviderWrapper {

>

>         public FilteringReflectionProvider(final ReflectionProvider

> reflectionProvider) {

>             super(reflectionProvider);

>         }

>

>         public void visitSerializableFields(final Object object, final

> Visitor visitor) {

>             wrapped.visitSerializableFields(object, new Visitor() {

>                 public void visit(String name, Class type, Class

> definedIn, Object value) {

>                     if (!name.equals("targetObject")) {

>                         visitor.visit(name, type, definedIn, value);

>                     }

>                 }

>             });

>         }

>     }

> }

>

> xstream.registerConverter(new

> OmittingReflectionConverter(xstream.getMapper(),

> xstream.getReflectionProvider()));

>

> - Jörg

>

>

> ---------------------------------------------------------------------

> To unsubscribe from this list, please visit:

>

>     http://xircles.codehaus.org/manage_email

>

>

>

>

>

> ---------------------------------------------------------------------

> To unsubscribe from this list, please visit:

>

>     http://xircles.codehaus.org/manage_email

>

>

>

>

 

--

View this message in context: http://www.nabble.com/Skip-field-during-deserialization-tp25649982p25983135.html

Sent from the xstream - user mailing list archive at Nabble.com.

 

 

---------------------------------------------------------------------

To unsubscribe from this list, please visit:

 

    http://xircles.codehaus.org/manage_email

 

 


RE: RE: Re: Skip field during deserialization

by Jörg Schaible-2 :: Rate this Message:

Reply to Author | View Threaded | Show Only this Message

Hi,

darniz wrote at Dienstag, 20. Oktober 2009 23:48:

> Is there any update on this.
> This is a big issue since any extra element in the xml response will blow
> off your code.

*This* is not about *any extra element in the xml*. It is a very specific
case that did not work for Derek and maybe you start describing what you
actually do.
 
> Any update when this issue will be fixed.

XStream is for *Java to XML and back* in first place. It is the desired
behaviour that any XML element corresponds with a field in the Java object
(since it has been written that way). An unknown XML tag means that the
Java model does no longer match the serialized (XML-)version. This is not
different from Java serialization. So there is nothing to be *fixed*, you
might however have a feature request - but then explain your use case.

- Jörg


---------------------------------------------------------------------
To unsubscribe from this list, please visit:

    http://xircles.codehaus.org/manage_email



RE: RE: Re: Skip field during deserialization

by darniz :: Rate this Message:

Reply to Author | View Threaded | Show Only this Message

Sorry i think my  statement was not clear.

My issue is that if i have an element in  my xml like updateDate like this

<Post>
   <id>123</id>
   <updateDate>12/23/2009</updateDate>
</Post>
In my post class if i dont have property updateDate it will blow off. I know i have a contract from our vendor but sometimes there are some extra fields in the message which i want to ignore.

How can i do this.

RE: RE: Re: Skip field during deserialization

by Jörg Schaible-2 :: Rate this Message:

Reply to Author | View Threaded | Show Only this Message

Hi,

darniz wrote:

>
> Sorry i think my  statement was not clear.
>
> My issue is that if i have an element in  my xml like updateDate like this
>
> <Post>
>    <id>123</id>
>    <updateDate>12/23/2009</updateDate>
> </Post>
> In my post class if i dont have property updateDate it will blow off. I
> know i have a contract from our vendor but sometimes there are some extra
> fields in the message which i want to ignore.
>
> How can i do this.

It depends whether you know which fields can come additionally or not. You
have three options:

1/ use omitField:

If your Post element corresponds to Post.class and this type is handled by
an reflection based converter (the default), then you can use the omitField
call:

xstream.omitField(Post.class, "updateDate");

However, this only has an effect, if your Post type actually has no field of
such a name (Derek's case).

2/ use a special custom converter that overwrites shouldSerializeMember

This solution was proposed by Brett in the other mail. A reflection based
converter will now ignore any unknown XML elements (i.e. any element that
does not have a corresponding member field). However, this will also turn
off the implicit collections, since the condition above also applies to
those.

3/ use a custom converter

You may write an own converter for your Post type (have a look at the
converter tutorial, it's easy). Here you can ask the reader for the current
tag name and decide yourself whether you know this element or not.

- Jörg


---------------------------------------------------------------------
To unsubscribe from this list, please visit:

    http://xircles.codehaus.org/manage_email



RE: RE: Re: Skip field during deserialization

by darniz :: Rate this Message:

Reply to Author | View Threaded | Show Only this Message

I am writing a custom connverter since to unmarshall my xml.  A little bit of history about my code
My xml looks like
<posts>
    <post id="222">
        <title>Car post</title>
        <updateDate>12/23/2009</updateDate>
        all other fields.
    </post>
</posts>
Here is my unmarshall method snipped. the problem happens when i call
post = (Post)context.convertAnother(posts,Post.class); thats where it throws the exception and tells me that updateDate was not able to be mapped. since updateDate is not mentioned as a member variable in my class.
i hope its clear i can give you the stack trace if you want, since i have to figure out a way to come out of it.

        while (reader.hasMoreChildren()) {
            reader.moveDown();
            cnt++;
            if ("post".equals(reader.getNodeName())){
                logger.debug(cnt);
                post = (Post)context.convertAnother(posts,Post.class);
            }
            reader.moveUp();
        }

Thanks
darniz

RE: RE: Re: Skip field during deserialization

by Trumbo, Derek :: Rate this Message:

Reply to Author | View Threaded | Show Only this Message

If your only issue is that the updateDate field does not exist in the class you're deserializing:

public class Post {
   String title;
   //no updateDate field any longer (it used to exist or exists in the code where XML was created)
   all other fields.
}

Then I believe you can just call:

xstream.omitField(Post.class, "updateDate");

Before you call fromXML() and you won't need a custom converter.  If you have other problems you're addressing, you might need a custom converter.

-----Original Message-----
From: darniz [mailto:rnizamuddin@...]
Sent: Wednesday, October 21, 2009 12:16 PM
To: user@...
Subject: RE: RE: Re: [xstream-user] Skip field during deserialization


I am writing a custom connverter since to unmarshall my xml.  A little bit of history about my code My xml looks like <posts>
    <post id="222">
        <title>Car post</title>
        <updateDate>12/23/2009</updateDate>
        all other fields.
    </post>
</posts>
Here is my unmarshall method snipped. the problem happens when i call post = (Post)context.convertAnother(posts,Post.class); thats where it throws the exception and tells me that updateDate was not able to be mapped. since updateDate is not mentioned as a member variable in my class.
i hope its clear i can give you the stack trace if you want, since i have to figure out a way to come out of it.

        while (reader.hasMoreChildren()) {
            reader.moveDown();
            cnt++;
            if ("post".equals(reader.getNodeName())){
                logger.debug(cnt);
                post = (Post)context.convertAnother(posts,Post.class);
            }
            reader.moveUp();
        }

Thanks
darniz
--
View this message in context: http://www.nabble.com/Skip-field-during-deserialization-tp25649982p25997562.html
Sent from the xstream - user mailing list archive at Nabble.com.


---------------------------------------------------------------------
To unsubscribe from this list, please visit:

    http://xircles.codehaus.org/manage_email





---------------------------------------------------------------------
To unsubscribe from this list, please visit:

    http://xircles.codehaus.org/manage_email



RE: RE: Re: Skip field during deserialization

by darniz :: Rate this Message:

Reply to Author | View Threaded | Show Only this Message

I do have a reason to write a custom converter The xml whcih my  unmarshall takes is hierarchial and it gets mapped to my object graph which is 3 levels deep. Then i convert it to my domain object which is just flat since we are indexing it into solr. I tried the omit field it doesn't work, here is my entire code

public List<? extends GlobalItem> unmarshal(HierarchicalStreamReader reader,UnmarshallingContext context) {

        Posts posts = new Posts();
        List<ForumItem> forumItemList = new ArrayList<ForumItem>();

        int cnt = 0;
        Post post = null;
        ForumItem forumItem = null;
        while (reader.hasMoreChildren()) {
            reader.moveDown();
            cnt++;
            if ("post".equals(reader.getNodeName())){
                logger.debug(cnt);
                forumItem = new ForumItem();
                forumItem.setSubjectType("forums");
                forumItem.setSite("edmunds");
                post = (Post)context.convertAnother(posts,Post.class);
                forumItem.setId("forums:" + post.getId());
                //if the deleted xml element is present.
                if (post.getDeleted()!=null && forumItem.getTitle()==null){
                    forumItem.setDeleted(true);
                }else{
                    forumItem.setTitle(post.getTitle());
                    forumItem.setAuthor(post.getAuthors().get(0));
                    //TODO check for null and write a common method which takes the date
                    //format which it want to convert.
                    forumItem.setPostedDate(
                        SearchDataUtils.convertStringToDate(post.getPostedDate(),"yyyy-MM-dd hh:mm:ss"));
                    forumItem.setUpdateDate(
                        SearchDataUtils.convertStringToDate(post.getUpdateDate(),"yyyy-MM-dd hh:mm:ss"));
                    forumItem.setThread(post.getThread());
                    forumItem.setTags(post.getTags());
                    forumItem.setBody(post.getBody());
                    Forum forum = post.getForum();
                    if (forum!=null){
                        forumItem.setForumTitle(forum.getTitle());
                        forumItem.setForumHosts(forum.getHosts().getHosts());
                    }
                }
                forumItemList.add(forumItem);
            }
            reader.moveUp();
        }
        return forumItemList;
    }

RE: RE: Re: Skip field during deserialization

by Jörg Schaible-2 :: Rate this Message:

Reply to Author | View Threaded | Show Only this Message

darniz wrote:

>
> I am writing a custom connverter since to unmarshall my xml.  A little bit
> of history about my code
> My xml looks like
> <posts>
>     <post id="222">
>         <title>Car post</title>
>         <updateDate>12/23/2009</updateDate>
>         all other fields.
>     </post>
> </posts>
> Here is my unmarshall method snipped. the problem happens when i call
> post = (Post)context.convertAnother(posts,Post.class); thats where it
> throws the exception and tells me that updateDate was not able to be
> mapped. since updateDate is not mentioned as a member variable in my
> class. i hope its clear i can give you the stack trace if you want, since
> i have to figure out a way to come out of it.
>
>         while (reader.hasMoreChildren()) {
>             reader.moveDown();
>             cnt++;
>             if ("post".equals(reader.getNodeName())){
>                 logger.debug(cnt);
>                 post = (Post)context.convertAnother(posts,Post.class);
>             }
>             reader.moveUp();
>         }

Yes, because you need a custom converter for Post.class. Your snippet is
from a custom converter that handles the type which corresponds to
the 'posts' tag.

- Jörg



---------------------------------------------------------------------
To unsubscribe from this list, please visit:

    http://xircles.codehaus.org/manage_email



RE: RE: Re: Skip field during deserialization

by darniz :: Rate this Message:

Reply to Author | View Threaded | Show Only this Message

So is there a way since omit field doesn't work i tried giving like this.
xstream.omitField(Post.class,"updateDate");

Thats what not working

RE: RE: RE: Re: Skip field during deserialization

by Trumbo, Derek :: Rate this Message:

Reply to Author | View Threaded | Show Only this Message

It seems that the common issue is:

"Pretend an XML element and all of its children elements do not exist in the XML when deserializing."

Jorg,

I can't say I know how common a use case this is, but do you think if there was enough need for this feature that it could be elevated to a first-level feature in XStream?  i.e. so that custom converters were not needed to perform this function?  

It's hard to describe the specific use cases but I would guess they would boil down to that the Java model no longer corresponds to the model that existed when the XML was written (as you mentioned) AND the developer is aware of the discrepancy and conscientiously needs to ignore parts of the XML.

Or would this violate too many of the principles inherent in XStream?  I.e. Extensibility, elegant design, etc.?

Thank you

-----Original Message-----
From: news [mailto:news@...] On Behalf Of Jörg Schaible
Sent: Wednesday, October 21, 2009 11:48 AM
To: user@...
Subject: [xstream-user] RE: RE: Re: Skip field during deserialization

Hi,

darniz wrote:

>
> Sorry i think my  statement was not clear.
>
> My issue is that if i have an element in  my xml like updateDate like
> this
>
> <Post>
>    <id>123</id>
>    <updateDate>12/23/2009</updateDate>
> </Post>
> In my post class if i dont have property updateDate it will blow off.
> I know i have a contract from our vendor but sometimes there are some
> extra fields in the message which i want to ignore.
>
> How can i do this.

It depends whether you know which fields can come additionally or not. You have three options:

1/ use omitField:

If your Post element corresponds to Post.class and this type is handled by an reflection based converter (the default), then you can use the omitField
call:

xstream.omitField(Post.class, "updateDate");

However, this only has an effect, if your Post type actually has no field of such a name (Derek's case).

2/ use a special custom converter that overwrites shouldSerializeMember

This solution was proposed by Brett in the other mail. A reflection based converter will now ignore any unknown XML elements (i.e. any element that does not have a corresponding member field). However, this will also turn off the implicit collections, since the condition above also applies to those.

3/ use a custom converter

You may write an own converter for your Post type (have a look at the converter tutorial, it's easy). Here you can ask the reader for the current tag name and decide yourself whether you know this element or not.

- Jörg


---------------------------------------------------------------------
To unsubscribe from this list, please visit:

    http://xircles.codehaus.org/manage_email





---------------------------------------------------------------------
To unsubscribe from this list, please visit:

    http://xircles.codehaus.org/manage_email



RE: RE: RE: Re: Skip field during deserialization

by Jörg Schaible-2 :: Rate this Message:

Reply to Author | View Threaded | Show Only this Message

Hi Derek,

Trumbo, Derek wrote:

> It seems that the common issue is:
>
> "Pretend an XML element and all of its children elements do not exist in
> the XML when deserializing."
>
> Jorg,
>
> I can't say I know how common a use case this is, but do you think if
> there was enough need for this feature that it could be elevated to a
> first-level feature in XStream?  i.e. so that custom converters were not
> needed to perform this function?
>
> It's hard to describe the specific use cases but I would guess they would
> boil down to that the Java model no longer corresponds to the model that
> existed when the XML was written (as you mentioned) AND the developer is
> aware of the discrepancy and conscientiously needs to ignore parts of the
> XML.

But exactly in this case the developer knows very well the elements to
ignore and that's where he can use the omitField method.

> Or would this violate too many of the principles inherent in XStream?
> I.e. Extensibility, elegant design, etc.?

The point is that ignoring *arbitrary* XML fields *is* dangerous after all.
However, a long standing requirement for a customizable ErrorHandling model
exists therefore in JIRA.

- Jörg



---------------------------------------------------------------------
To unsubscribe from this list, please visit:

    http://xircles.codehaus.org/manage_email



RE: RE: Re: Skip field during deserialization

by Jörg Schaible-2 :: Rate this Message:

Reply to Author | View Threaded | Show Only this Message

darniz wrote:

>
> So is there a way since omit field doesn't work i tried giving like this.
> xstream.omitField(Post.class,"updateDate");
>
> Thats what not working


Which version of XStream you're using? Please post the code where you setup
the xstream and the *complete* stack trace.

- Jörg


---------------------------------------------------------------------
To unsubscribe from this list, please visit:

    http://xircles.codehaus.org/manage_email



RE: RE: RE: Re: Skip field during deserialization

by darniz :: Rate this Message:

Reply to Author | View Threaded | Show Only this Message


Sorry for making this thread long.
The only issue i have is that if the xml response by a third party by chance have an element in our case like <updateDate> which we were not aware of xstream should not error out. For example when we use castor or jibx we can define mapping between xml element and our java object model and if there are some extra xml element in the message it wont fail and it gets ignored as far as i know.
Simialary for xstream too what ever property is defined in the class should gets populated and other xml element should be ignored.

That will be much helpful. and for final time could you guys please tell me  again what will be the best practice to tackle this

darniz

RE: RE: RE: RE: Re: Skip field during deserialization

by Trumbo, Derek :: Rate this Message:

Reply to Author | View Threaded | Show Only this Message

I see.  Thinking of it again, I suppose I was confusing two use cases, sorry about that.  This feature probably would only be useful in the case that the corresponding field still exists in the Java object and you want to leave the field uninitialized, a topic which we've already discussed, and for which I made that minor-priority JIRA entry.  I thought for a second there was a second application.

Thanks.

-----Original Message-----
From: news [mailto:news@...] On Behalf Of Jörg Schaible
Sent: Wednesday, October 21, 2009 12:55 PM
To: user@...
Subject: [xstream-user] RE: RE: RE: Re: Skip field during deserialization

Hi Derek,

Trumbo, Derek wrote:

> It seems that the common issue is:
>
> "Pretend an XML element and all of its children elements do not exist
> in the XML when deserializing."
>
> Jorg,
>
> I can't say I know how common a use case this is, but do you think if
> there was enough need for this feature that it could be elevated to a
> first-level feature in XStream?  i.e. so that custom converters were
> not needed to perform this function?
>
> It's hard to describe the specific use cases but I would guess they
> would boil down to that the Java model no longer corresponds to the
> model that existed when the XML was written (as you mentioned) AND the
> developer is aware of the discrepancy and conscientiously needs to
> ignore parts of the XML.

But exactly in this case the developer knows very well the elements to ignore and that's where he can use the omitField method.

> Or would this violate too many of the principles inherent in XStream?
> I.e. Extensibility, elegant design, etc.?

The point is that ignoring *arbitrary* XML fields *is* dangerous after all.
However, a long standing requirement for a customizable ErrorHandling model exists therefore in JIRA.

- Jörg



---------------------------------------------------------------------
To unsubscribe from this list, please visit:

    http://xircles.codehaus.org/manage_email





---------------------------------------------------------------------
To unsubscribe from this list, please visit:

    http://xircles.codehaus.org/manage_email


< Prev | 1 - 2 | Next >