Don't send zeros in JSON response

I am 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 am sending 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 send "blocks": null

?

I am developing an Android client to parse JSON data. How can I deal with null

?

+3


source to share


2 answers


You may be able to avoid sending the default value for 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 what null

is a valid value in JSON and should be processed when there is a chance that there may not be data attached to your entity. In your javascript, it might be easier to have an if condition:



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 a given item has a specific list of blocks, you will most likely have to go with the last option to check that a block item is not null.

+4


source


You have several options that I see.

  • Keep sending zeros to JSON and validate client side with invalidation by handling it there.

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

  • Just don't include objects that are null. (i.e. send an object with FormId and FormName fields, but no block fields).



Whichever you choose, it's important to communicate in your API what happens if something doesn't exist. And be consistent.

0


source







All Articles