Skip to main content

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index] [List Home]
Re: [eclipselink-users] MOXY: Map empty element as Boolean

Hi Magnus,

You could do this by using a combination of a Converter and a NullPolicy on a DirectMapping, which is slightly more work to map, but makes your object model better.

You would need to do something like:
XMLDirectMapping mapping = new XMLDirectMapping();
mapping.setAttributeName("something");
mapping.setXPath("something/text()");
mapping.getNullPolicy().setNullRepresentedByEmptyNode(false);
mapping.setConverter(new MyBooleanConverter());

The way this mapping is currently set up, an empty node in the XML will come back as "" and an absent node in the XML will come back as null. The converter just needs to handle the conversion from those values to a boolean:

            @Override
            public Object convertObjectValueToDataValue(Object objectValue, Session session, XMLMarshaller marshaller) {
                if(objectValue == Boolean.FALSE) {
                    return null;
                }
                return "";
            }

            @Override
            public Object convertDataValueToObjectValue(Object dataValue, Session session, XMLUnmarshaller unmarshaller) {
                if(dataValue == null) {
                    return Boolean.FALSE;
                } else {
                    return Boolean.TRUE;
                }
            }
      
Hope this helps,

-Matt
On 10/02/2011 7:25 AM, Magnus Heino wrote:

I have this class;

class Foo {
  Boolean something;
}


This xml:

<foo>
  <something/>
</foo>

...should create a mapped instance that has something = Boolean.TRUE;

This xml:

<foo>
</foo>

...should create a mapped instance that has something = Boolean.FALSE;

How can I do this? I cannot find a way to map this to a Boolean. 

Right now I create a descriptor for a dummy class, and map that instead of the boolean. Then i get null or dummy object instead of false and true

        XMLChoiceObjectMapping something = new XMLChoiceObjectMapping();
        something.setAttributeName("something");
        allvarligtFelIR.addChoiceElement("something", Dummy.class);

But this feels wrong, and I really want a Boolean....

Thanks!

--

  /Magnus Heino

_______________________________________________ eclipselink-users mailing list eclipselink-users@xxxxxxxxxxx https://dev.eclipse.org/mailman/listinfo/eclipselink-users

Back to the top