Suppress empty List of Objects from Json output

127 views Asked by At

I have a Data class which I populate manually from a XML returned from a trading Partner. Most of time the returned Data will only have a few of the fields in my class populated, the others I set to Nothing(null) and then use the

Dim settings As New JsonSerializerSettings
settings.NullValueHandling = NullValueHandling.Ignore

to suppress any field with no data. All that works great but I am wondering how I can do the same or similar for List of Objects in my class. Right now if there is no data for one of these I still get an an output like this which is an empty json Array.

{
    "Txnum": "APO100000007R",
    "Dtsent": "20180625105938",
    "Txtyp": "A",
    "Location": [],
    "Terminationdata": [],
    "Responsestatus": {
        "prespc": "FTRAVQ059",
        "prespd": "LV1 IS REQUIRED "
    }
}

So I am wondering if and how I could avoid this short of checking json string before I return it and strip the "Location": [], for example.

1

There are 1 answers

0
MisterniceGuy On

This is the code that worked for me. Just as a Side Node the ShouldSerialize"PropertyName:() is case sensitive so ShouldSerializeLocation() works while ShouldSerializelocation() does not. In Vb code normally is not case sensitive so just watch for that to save your self some headache.

   <XmlElement([Namespace]:=SynchronossNS)>
    Public Property Location() As List(Of location)
        Get
            Return _location
        End Get
        Set
            _location = Value
        End Set
    End Property
    Public Function ShouldSerializeLocation() As Boolean
        Return _location.Count > 0

    End Function