如何将字符串值属性序列化为字符串数组 [英] How to serialize a string-valued property as a string array
问题描述
我有一堂课
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';
现在,当我将文件另存为json时:
Now when I save into the database as json:
Newtonsoft.Json.JsonConvert.SerializeObject(edited)
它在json中给了我
{"extratypes":"1,2"}
在像下面那样保存它之前,如何操作它为字符串数组:
How can I manipulate it to string array before saving it like the one below:
{"extratypes":["1","2"]}
推荐答案
您可以使用代理属性,该属性将字符串与数组进行转换.使用 [JsonIgnore]
装饰原始属性,并使用 [JsonProperty("extratypes")]
.如果方便的话,可以将代理属性设置为私有,只要它具有[JsonProperty]
属性,就会对其进行序列化:
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
示例小提琴.
其他选择是编写您自己的 JsonConverter
.
Other option would be to write your own JsonConverter
.
这篇关于如何将字符串值属性序列化为字符串数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!