WCF REST and JSON - Serialization and empty elements
I am returning a list of items 开发者_JAVA技巧(user defined class) in a REST service using WCF. I am returning the items as JSON and it is used in some client side javascript (so the 'schema' of the class was derived from what the javascript library required). The class is fairly basic, strings and a bool. The bool is optional, so if it is absent the javascript library uses a default value, and if it is present (true or false) the value is used.
The problem is if I use a bool, the value is defaulted to false when serialized, and if i use a bool?, the member is still sent accross in the JSON and defaulted to null which causes problems with the library (it wont fall back to the default value).
I know I can probably mess around the the javascript library, but I would like to find a way to just not send any members which are null so they dont show up in the serialized JSON at all.
Any ideas?
You could do a little bit of packing and unpacking before and after the serialization. E.g.:
- You could make two different versions of the class, one with and one without the bool, and convert as appropriate before and after transmitting. (sends the least amount of data, if # of bytes is a greater consideration than code complexity)
- You could add another bool that tells whether the first bool is supposed to be null.
精彩评论