2

I have classes which I serialize to a JSON String. For that, I'm using Newtonsoft.Json

It looks like this:

<JsonObject()>
Public Class MyClass

    Private _a;
    Private _b;

    Public Sub New(ByVal an As String, ByVal b as String)
        _a = a
        _b = b
    End Sub

    Public Property a As String
        Get
            Return _a
         End Get
         Protected Set(value As String)
             _a = value
         End Set
    End Property

    Public Property b As String
        Get
            Return _b
        End Get
        Protected Set(value As String)
            _b = value
        End Set
    End Property

End Class

I put them in a list and serialize this:

JsonConvert.SerializeObject(listMyObject)

But sometimes I don't need every Property in my JSON String. Is it possible to serialize properties I passed to the constructor? As in this case?:

Public Sub New(ByVal an As String)
    _a = a
End Sub
djv
  • 15,168
  • 7
  • 48
  • 72
BR75
  • 633
  • 7
  • 25

2 Answers2

3

You can use the attribute <JsonIgnore> over the properties you don't want to serialize

Stefano Cavion
  • 641
  • 8
  • 16
3

Check out Newtonsoft json Serialize Conditional Property.

This answer in C# demonstrates it in action.

In your case,

<JsonObject()>
Public Class MyClassName

    Public Property A As String
    Private ReadOnly _shouldSerializeA As Boolean
    Public Function ShouldSerializeA() As Boolean
        Return _shouldSerializeA
    End Function

    Public Property B As String
    Private ReadOnly _shouldSerializeB As Boolean
    Public Function ShouldSerializeB() As Boolean
        Return _shouldSerializeB
    End Function

    Public Sub New(ByVal a As String, ByVal b As String)
        Me.A = a
        Me.B = b
        Me._shouldSerializeA = True
        Me._shouldSerializeB = True
    End Sub

    Public Sub New(ByVal a As String)
        Me.A = a
        Me._shouldSerializeA = True
        Me._shouldSerializeB = False
    End Sub

End Class
djv
  • 15,168
  • 7
  • 48
  • 72