Search code examples
jsonvb.netwcfobjectproperties

Deserialize JSON object which has property name as number into a object in VB.NET


I have below JSON object

myvalues : {
     0 : "value0",
     1 : "value1",
     2 : "value2",
     3 : "value3"
}

I want to bind this JSON object into a vb.net class object as an input to a WCF OperationContract method - but I can't define the numeric property names as numbers. I am getting the error message:

Identifier expected on property names because property name cannot be a number

Using the following:

Public class myvalues_class

    public property 0 as string
    public property 1 as string
    public property 2 as string
    public property 3 as string

end class

how can I convert this JSON object to a vb.net object class?


Solution

  • uses DataContractJsonSerializer, so you will need to annotate your Values type with data contract attributes that map some validly-named vb.net properties to the JSON numeric property names, e.g. like so:

    <System.Runtime.Serialization.DataContract> _
    Public Class Values
        <DataMember(Name:="0")> _
        Public Property r As Integer
    
        <DataMember(Name:="1")> _
        Public Property g As Integer
    
         <DataMember(Name:="2")> _
        Public Property b As Integer
    
        <DataMember(Name:="3")> _
        Public Property a As Integer
    End Class
    

    Note that the data contract serializers are opt-in so you will have to mark all properties to be serialized with DataMemberAttribute.