问题
I have a class:
Public Class ExtraInfo
Property extratypes As String
End Class
I have a form submitted and the value assign is string, the data submitted from form is string not array:
extratypes = '1,2';
Now when I save into the database as json:
Newtonsoft.Json.JsonConvert.SerializeObject(edited)
it give me this in json:
{"extratypes":"1,2"}
How can I manipulate it to string array before saving it like the one below:
{"extratypes":["1","2"]}
回答1:
Use an array in your model:
Public Class ExtraInfo
Property extratypes() As String
End Class
and then Split the value that comes from the user input before assigning it to this property.
回答2:
You could use a proxy property that translates your string to and from an array. Decorate the original property with [JsonIgnore] and the proxy with [JsonProperty("extratypes")]. You can make the proxy property private if that's convenient and Json.NET will serialize it as long as it has the [JsonProperty]
attribute:
Public Class ExtraInfo
<JsonIgnore()> _
Public Property extratypes As String
<JsonProperty("extratypes")> _
Private Property extratypesArray As String()
Get
If extratypes Is Nothing Then
Return Nothing
End If
Return extraTypes.Split(","c)
End Get
Set(ByVal value As String())
If value Is Nothing Then
extratypes = Nothing
Else
extratypes = String.Join(","c, value)
End If
End Set
End Property
End Class
Sample fiddle.
Other option would be to write your own JsonConverter.
来源:https://stackoverflow.com/questions/34249342/how-to-serialize-a-string-valued-property-as-a-string-array