简体   繁体   中英

DataMember ignored when serializing to JSON

I have added DataMemeber to my object properties to change settings when serializing to JSON, however it is not using them. I have attempted to change the name, as well as emitting default values.

My reason for trying to do this is I want to ignore a property if it is at its default value.

I am attempting to use the Microsoft libraries and not the Newtonsoft ones.

    <DataMember(EmitDefaultValue:=True, IsRequired:=False, Name:="addressTable")> Public Property addressTable() As String
        Get
            Return _AddressTable
        End Get
        Set(ByVal value As String)
            _AddressTable = value
        End Set
    End Property


Public Function gObjToStr(ByVal InputObject As Object) As String

    Dim stream1 As New IO.MemoryStream
    Dim ser As Runtime.Serialization.Json.DataContractJsonSerializer = New Runtime.Serialization.Json.DataContractJsonSerializer(InputObject.GetType)

    ser.WriteObject(stream1, InputObject)
    stream1.Position = 0

    Dim sr As New IO.StreamReader(stream1)
    Dim OutString As String = Nothing

    Return sr.ReadToEnd

End Function

You need to remove the EmitDefaultValue attribute from the Property addressTable .

Basically, EmitDefaultValue tells the serialization engine whether to serialize the default value for a field or property being serialized .

The default value for EmitDefaultValue is true, so even if a property has a default value it would be serialized. As per your requirement, if you need to ignore a property, if it has default value then you need to add attribute EmitDefaultValue to the Property and set the value as false, [DataMember(EmitDefaultValue =false)] . In the code posted above, you have set the EmitDefaultValue = true , hence it is generating the addressTable in Serialization.

Also, IsRequired instructs the serialization engine that the member must be present when reading or deserializing . So you should be careful with usage of both Attributes EmitDefaultValue & IsRequired . The default value for IsRequired = false . So you can't have a combination like EmitDefaultValue=false and IsRequired=true , in this case Serialization engine would throw an exception.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM