Re: Prevent null property serialization for XML?

541 views
Skip to first unread message

Reyes Exclaim

unread,
Jul 19, 2012, 3:55:37 PM7/19/12
to jso...@googlegroups.com
I did find this in the examples but it doesn't seem to work for the XmlWriter:

        [JsonSpecifiedProperty("hasSomeURL")]
        public string someURL { get; set; }

        [JsonIgnore]
        public bool hasSomeURL
        {
            get { return this.someURL != null; }
        }

Stephen McKamey

unread,
Jul 19, 2012, 4:47:14 PM7/19/12
to jso...@googlegroups.com
Make sure that if you are using attributes like that, that you also specify the corresponding name resolution strategy in your data reader/writer settings which gets passed into the reader / writer. By default it uses a POCO strategy which doesn't look for attributes. The architecture of JsonFx v2 is such that the XmlWriter uses the same object walker as the JSON path.

Reyes Exclaim

unread,
Jul 19, 2012, 5:50:30 PM7/19/12
to jso...@googlegroups.com
Yes, that was it. Much thanks! I didn't realize how that worked.

Reyes Exclaim

unread,
Jul 19, 2012, 6:10:44 PM7/19/12
to jso...@googlegroups.com
I tried it with the JsonResolverStrategy and that worked with the attributes. I wondered though if I'm using the same resolver strategy and the XML and JSON are using the same walker if I removed the attributes would the XML behave like the JSON and not emit the null properties but that didn't work, so I will just leave the attributes in. I guess that null checking code is elsewhere. It would be nice to not have to use the attributes and extra methods, but I can't argue with, "it works, just do it this way".

Basically what I'm doing is allowing the client app to request full or partial data but using the same object with less properties filled in.

Thanks again!

On Thursday, July 19, 2012 4:47:14 PM UTC-4, Stephen McKamey wrote:

Stephen McKamey

unread,
Jul 19, 2012, 6:28:05 PM7/19/12
to jso...@googlegroups.com
Two other possible solutions which may involve less boilerplate code:

1) Use the built-in XmlResolverStrategy which does ignore null values (plus a bunch of other stuff including enabling some of the .NET framework XML serialization attributes).

2) If all you want is to not serialize if is null, it might make most sense to write your own IResolverStrategy. You will find it is a pretty simple interface and it gives a lot of control. This way you only write the check in one place, not in addition to every single property. The JsonSpecifiedProperty attribute was intended for more complex scenarios than "not null" where you couldn't statically define a default value but perhaps needed to check state on other members dynamically.
Reply all
Reply to author
Forward
0 new messages