How to serialize a string-valued property as a string array

别说谁变了你拦得住时间么 提交于 2019-12-25 01:49:24

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!