VansFannel
VansFannel

Reputation: 45921

Don't send nulls on JSON response

I'm developing a Rest web service with WCF.

I have the following contract:

    namespace ADM.Contracts
    {
        [DataContract]
        public class FormContract
        {
            [DataMember]
            public int FormId { get; set; }

            [DataMember]
            public string FormName { get; set; }

            [DataMember]
            public List<BlockContract> blocks { get; set; }
        }

}

Sometimes, blocks are null and I send this JSON:

[
    {
        "FormId": 1,
        "FormName": "Formulario 1",
        "blocks": null
    },
    {
        "FormId": 2,
        "FormName": "Formulario 2",
        "blocks": null
    },
    {
        "FormId": 3,
        "FormName": "Formulario 3",
        "blocks": null
    }
]

Can I avoid sending "blocks": null?

I'm developing an Android client to parse JSON data. How can I deal with null?

Upvotes: 3

Views: 2498

Answers (2)

villecoder
villecoder

Reputation: 13483

You should be able to avoid sending the default value of the list member (which is null) by adding to your DataMember attribute.

[DataMember(Name = "blocks", IsRequired=false, EmitDefaultValue=false)]
public List<BlockContract> blocks { get; set; }

However, keep in mind that null is a valid value in JSON and should be handled when there is the possibility that there could be no data attached to your entity. It could just be easier in your javascript to have an if condition like:

for(var i = 0; i < data.length; ++i) {
   if (data[i].blocks != null) {
      //do stuff
   } else {
      //no blocks. do other stuff
   }
}

Edit: I would like to point out that if you need to check if the data member in question has a blocks list defined, you will most likely have to go with the latter option of checking that the blocks member is not null.

Upvotes: 6

smcg
smcg

Reputation: 3273

You have a couple of options that I see.

  1. Keep sending nulls in the JSON and check for nullity client-side, handling it there.

  2. Check for nullity in your resource class and send something else instead (empty object, new object with empty fields, object with placeholder fields).

  3. Just don't include objects that are null. (ie send an object with FormId and FormName fields but no blocks field).

Whatever you choose it's important to communicate in your API what will happen if something doesn't exist. And be consistent.

Upvotes: 0

Related Questions