Home > Mobile >  value of type string cannot be converted to list(of string) VB.Net
value of type string cannot be converted to list(of string) VB.Net

Time:02-14

I am serializing the data structure to xml but i am getting the Error

Data Structure

Public Class Product
Public Id As Integer
Public name As String
Public quantity As Integer
Public price As Integer
Public Property state As List(Of States)

Public Sub New()
End Sub

Public Sub New(ByVal name As String,
               ByVal quantity As Integer,
               ByVal price As Integer,
               ByVal state As List(Of States)
               )
    Me.name = name
    Me.quantity = quantity
    Me.price = price
    Me.state = state
End Sub
End Class

Public Class States
    <XmlArrayItem("State")>
    Public Property state As List(Of String)
    Public Sub New()
    End Sub

    Public Sub New(state As List(Of String))
        state = New List(Of String)()
    End Sub
End Class

This is how I am passing the data

        Dim countries As New List(Of Product) From
    {
        New Product With {.name = "Pakistan", .quantity = 1, .price = 50, .state = New List(Of States) From
        {
            New States With {.state = "KPK"},
            New States With {.state = "Punjab"},
            New States With {.state = "Sindh"}}},
        New Product With {.name = "Saudi Arabia", .quantity = 2, .price = 100, .state = New List(Of States) From
        {
            New States With {.state = "Makkah"},
            New States With {.state = "Madina"},
            New States With {.state = "Jaddah"}}
        }
    }

I am getting the Error in States List i.e. (New States With {.state = "Makkah"}) it says value of type string cannot be converted to list(of string) I tried it in different way but this error is not going anywhere

My Serializer Code

Dim serialization As XmlSerializer = New XmlSerializer(GetType(List(Of Product)))
    serialization.Serialize(Console.Out, countries)
    Console.ReadLine()

I'm not sure what exactly is wrong with this code.

CodePudding user response:

Just as you create a List(Of States) for Product, you'd need to create a List(Of String) for States

Dim countries As New List(Of Product) From
    {
        New Product With {.name = "Pakistan", .quantity = 1, .price = 50, .state = New List(Of States) From
        {
            New States With {.state = New List(Of String) From {"KPK"}}, 'A list with one item
            New States With {.state = New List(Of String) From {"Punjab", "Sindh"} 'A list with two items
        }        
    }
  • Related