我正在尝试设置各种 JSON 属性序列化的顺序,我能找到的所有示例都使用 C#,如下所示:
[JsonProperty(Order = 1)]
Run Code Online (Sandbox Code Playgroud)
但我找不到一种方法可以在 Visual Studio 接受的 VB.NET 中编写此内容 - 显而易见的是:
<JsonProperty(Order = 1)>
Run Code Online (Sandbox Code Playgroud)
给出错误并且不会编译....(毫无疑问有一种方法可以格式化最后一行,但是...)
因为我还需要为同一属性设置属性名称,例如
[JsonProperty(PropertyName = "CardCode")]
Run Code Online (Sandbox Code Playgroud)
在 C# 中,如何使用 vb.net 设置名称和顺序JsonPropertyAttribute
?
在vb.net中应用带有参数的属性的语法在属性概述 (Visual Basic):属性参数中进行了描述:
属性参数
许多属性都有参数,这些参数可以是位置参数、未命名参数或命名参数。任何位置参数都必须按照一定的顺序指定,并且不能省略;命名参数是可选的,可以按任何顺序指定。首先指定位置参数。例如,这三个属性是等效的:
Run Code Online (Sandbox Code Playgroud)<DllImport("user32.dll")> <DllImport("user32.dll", SetLastError:=False, ExactSpelling:=False)> <DllImport("user32.dll", ExactSpelling:=False, SetLastError:=False)>
因此,如果您想应用JsonPropertyAttribute
属性并设置名称和顺序,则必须执行以下操作:
Public Class Card
<JsonProperty(PropertyName:="CardName", Order:=2)>
Public Property Name As String
<JsonProperty(PropertyName:="CardDescription", Order:=3, _
NullValueHandling := NullValueHandling.Ignore, DefaultValueHandling := DefaultValueHandling.IgnoreAndPopulate)>
<System.ComponentModel.DefaultValue("")>
Public Property Description As String
<JsonProperty(PropertyName:="CardCode", Order:=1)>
Public Property Code As String
End Class
Run Code Online (Sandbox Code Playgroud)
笔记:
如源代码AllowMultiple = false
中的设置所示,只能将 的一个实例应用于给定的成员或参数:JsonPropertyAttribute
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property | AttributeTargets.Parameter, AllowMultiple = false)]
public sealed class JsonPropertyAttribute : Attribute
{
// Contents of the type omitted
}
Run Code Online (Sandbox Code Playgroud)
因此,所有必要的JsonPropertyAttribute
设置都必须在该属性中初始化。
行继续字符_
可用于跨多行中断属性设置。然而,属性可以应用于紧邻属性之前的行,因此在这种情况下没有必要使用它。
根据JSON 标准, JSON 对象是一组无序的名称/值对,因此通常不需要指定顺序。
示例 VB.NET fiddle位于此处。