I am trying to set the order in which various JSON properties get serialised, and all the examples I can find are using C#, and are like:
[JsonProperty(Order = 1)]
but I cannot find a way to write this in VB.NET which Visual Studio will accept - the obvious:
<JsonProperty(Order = 1)>
gives errors and won't compile .... (no doubt there's a way to format that last line, but...)
As I also need to set the property name for the same property, e.g.
[JsonProperty(PropertyName = "CardCode")]
in c#, how can I set both the name and order in vb.net using JsonPropertyAttribute
?
The syntax for applying attributes with parameters in vb.net is described in Attributes overview (Visual Basic): Attribute Parameters:
Attribute Parameters
Many attributes have parameters, which can be positional, unnamed, or named. Any positional parameters must be specified in a certain order and cannot be omitted; named parameters are optional and can be specified in any order. Positional parameters are specified first. For example, these three attributes are equivalent:
<DllImport("user32.dll")> <DllImport("user32.dll", SetLastError:=False, ExactSpelling:=False)> <DllImport("user32.dll", ExactSpelling:=False, SetLastError:=False)>
Thus, if you want to apply JsonPropertyAttribute
to a property and set both the name and order, you must do:
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
Notes:
As shown by the setting AllowMultiple = false
in the source code, only one instance of JsonPropertyAttribute
can be applied to a given member or parameter:
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property | AttributeTargets.Parameter, AllowMultiple = false)]
public sealed class JsonPropertyAttribute : Attribute
{
// Contents of the type omitted
}
Thus all necessary JsonPropertyAttribute
settings must be initialized in that one attribute.
The line continuation character _
can be used to break attribute settings across multiple lines. Attributes can be applied on the line(s) immediately preceding a property, however, so it is not necessary to use it in this case.
According to the JSON standard a JSON object is an unordered set of name/value pairs, so it is often not necessary to specify the order.
Sample VB.NET fiddle here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With