DieVeenman DieVeenman - 4 months ago 14
Vb.net Question

Access Property of a child class from Parent class

Problem:

I have made a class from JSON which I got supplied from an external company used to send orders to their system

Part of the class:

Public Class SalesOrder
Public Class Field
Public Property Name() As String
Get
Return m_Name
End Get
Set(value As String)
m_Name = value
End Set
End Property
Private m_Name As String
Public Property FieldType() As String
Get
Return m_FieldType
End Get
Set(value As String)
m_FieldType = value
End Set
End Property
Private m_FieldType As String
End Class
End Class


Case:

Let's say I made a new instance of the SalesOrder class by taking a txt file with JSON and parsing the class from there, now I want to access the Name property inside of the Field class so I can edit it. How can I do this from a new instance of the SalesOrder class? Whenever I try to access it it will tell me it's a type and cannot be used as an expression

Example:

Dim sOrder As New SalesOrder
sOrder = JsonConvert.DeserializeObject(Of SalesOrder)(File.ReadAllText("C:\Users\Something\Documents\Visual Studio 2010\Projects\SomethingElse\WebApplication1\OrderDefinitionJSON.txt"))
Dim FieldName As String = SOrder.Field.Name


This will cause an exception at sOrder.Field

EDIT:

JSON

This is part of the JSON I'm trying to read out:

{
"BookDate": "2016-12-18T10:39:05.276Z",
"BusinessObject": "SO1",
"Table": {
"Definition": {
"Name": "SO_HDR",
"Fields": [{
"Name": "RowId",
"FieldType": "C"
}]
}
}
}


Thanks!

Answer

Your class SalesOrder doesn't contain an istance of Field class. You have to add a property to SalesOrder class if you want to set it:

Public Class SalesOrder
  Public SalesField as Field
End Class

Public Class Field
    Public Property Name() As String
        Get
            Return m_Name
        End Get
        Set(value As String)
            m_Name = value
        End Set
    End Property
    Private m_Name As String
    Public Property FieldType() As String
        Get
            Return m_FieldType
        End Get
        Set(value As String)
            m_FieldType = value
        End Set
    End Property
    Private m_FieldType As String
  End Class

Now, if you deserialized correctly and if SalesField is not nothing, you can:

Dim sOrder As New SalesOrder
            sOrder = JsonConvert.DeserializeObject(Of SalesOrder)(File.ReadAllText("C:\Users\Something\Documents\Visual Studio 2010\Projects\SomethingElse\WebApplication1\OrderDefinitionJSON.txt"))
                    Dim FieldName As String = SOrder.Field.Name