Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 267
VansFannel Avatar asked May 17 '26 11:05

VansFannel


1 Answers

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.

like image 87
villecoder Avatar answered May 20 '26 07:05

villecoder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!