【问题标题】:How to serialize only properties which passed to constructor?如何仅序列化传递给构造函数的属性?
【发布时间】:2020-02-06 16:14:57
【问题描述】:

我有我序列化为 JSON 字符串的类。为此,我正在使用 Newtonsoft.Json

看起来像这样:

<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

我将它们放在一个列表中并对其进行序列化:

JsonConvert.SerializeObject(listMyObject)

但有时我不需要 JSON 字符串中的每个属性。是否可以序列化我传递给构造函数的属性?在这种情况下?:

Public Sub New(ByVal an As String)
    _a = a
End Sub

【问题讨论】:

  • 去掉c#标签。
  • 这与c#vb.net 有什么关系?
  • @ThePerplexedOne - 请注意,任何用户都可以编辑帖子,包括标签。任何拥有 2000 或更高代表的用户都将立即应用编辑。
  • 我猜你想要有多个构造函数重载,并且根据创建对象时使用的哪个,你只想序列化特定的属性,对吗?

标签: .net json vb.net


【解决方案1】:

查看Newtonsoft json Serialize Conditional Property

C# 中的This answer 实际演示了它。

在你的情况下,

<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

【讨论】:

    【解决方案2】:

    您可以在不想序列化的属性上使用属性&lt;JsonIgnore&gt;

    【讨论】:

      猜你喜欢
      • 2010-11-17
      • 2016-03-24
      • 1970-01-01
      • 1970-01-01
      • 2020-05-03
      • 2023-03-16
      • 2013-09-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多