Results 1 to 6 of 6

Thread: Deserialising a JSON array

  1. #1

    Thread Starter
    Lively Member
    Join Date
    Aug 2021
    Posts
    117

    Deserialising a JSON array

    Dear Friends,

    After much help, I have progressed well with my project but I am now having trouble reading data from a Webservice JSON response. I have created classes for all components of the response as follows:

    Code:
        Public Class PCIResponse
            Public Property claimAssessment As claimAssessment
            Public Property status As String
            Public Property Count As Integer
        End Class
        Public Class claimAssessment
            Public Property claimId As String
            Public Property claimant As claimantPCResponse
            Public Property patient As patientPCResponse
            Public Property medicalEvent As IEnumerable(Of medicalEventPCresponse)
            Public Property error1 As errorPCresponse
        End Class
        Public Class claimantPCResponse
            Public Property currentMembership As currentMembership1
        End Class
        Public Class currentMembership1
            Public Property memberNumber As String
            Public Property memberRefNumber As String
        End Class
        Public Class patientPCResponse
            Public Property currentMembership As currentMembership2
        End Class
        Public Class currentMembership2
            Public Property memberNumber As String
            Public Property memberRefNumber As String
        End Class
        Public Class medicalEventPCresponse
            Public Property id As String
            Public Property eventDate As String
            Public Property service As IEnumerable(Of servicePCresponse)
        End Class
        Public Class servicePCresponse
            Public Property id As String
            Public Property assessmentCode As String
            Public Property benefitPaid As String
            Public Property chargeAmount As String
            Public Property itemNumber As String
            Public Property [error] As errorme
        End Class
        Public Class errorme
            Public Property code As String
            Public Property text As String
        End Class
        Public Class errorPCresponse
            Public Property code As String
            Public Property text As String
        End Class
    The arrays are medicalevent and service. I have deserialised the webresponse with the following vb code:

    Code:
    Dim responseObject = JsonConvert.DeserializeObject(Of PCIResponse)(resultPC)
    where resultPC is the webservice response.

    Here is a typical response:

    Code:
    {
      "claimAssessment" : {
        "medicalEvent" : [ {
          "service" : [ {
            "error" : {
              "code" : 9635,
              "text" : "Check Servicing Provider.  May not be able to provide the service for this item at date of service."
            },
            "id" : "A000",
            "assessmentCode" : "UNACCEPTABLE_ERROR",
            "chargeAmount" : "15600",
            "itemNumber" : "110"
          } ],
          "eventDate" : "2022-04-16",
          "id" : "01"
        }, {
          "service" : [ {
            "error" : {
              "code" : 9635,
              "text" : "Check Servicing Provider.  May not be able to provide the service for this item at date of service."
            },
            "id" : "A001",
            "assessmentCode" : "UNACCEPTABLE_ERROR",
            "chargeAmount" : "78000",
            "itemNumber" : "110"
          } ],
          "eventDate" : "2022-04-16",
          "id" : "02"
        } ],
        "claimId" : "THO0000010052022155354"
      },
      "status" : "MEDICARE_REJECTED"
    }
    Don't worry about the errors - they just reflect test data being submitted to the server.

    I can access the non-array elements, but I have tried a number of ways of iterating through the medicalevent and service arrays and none seem to work. How should I be going about it?

  2. #2
    PowerPoster PlausiblyDamp's Avatar
    Join Date
    Dec 2016
    Location
    Pontypool, Wales
    Posts
    2,458

    Re: Deserialising a JSON array

    You should be able to just do a For ... Each over the array elements, what code have you tried so far?

  3. #3

    Thread Starter
    Lively Member
    Join Date
    Aug 2021
    Posts
    117

    Re: Deserialising a JSON array

    If I try to do that with my current declarations I can't reach the array elements. For example, I can retrieve:

    Code:
    memberNumber = responseObject.claimAssessment.claimant.currentMembership.memberNumber
    but

    Code:
    eventDate = responseObject.claimAssessment.medicalEvent.eventDate
    flags that eventDate is not a member of IEnumerable(Of JSONUtility.medicalEventPCResponse), presumably because it is inside the array?

    Are you thinking that I just try declaring the array elements without the IEnumerable and then loop? Because if I do that then I can define them, but the deserialize fails as it needs an IEnumerable ?

    I have also tried to deserialise the array alone, but the obvious syntaxes don’t allow me to do that, but is there a way to do that?
    Last edited by Bear89; May 10th, 2022 at 05:23 AM.

  4. #4
    PowerPoster PlausiblyDamp's Avatar
    Join Date
    Dec 2016
    Location
    Pontypool, Wales
    Posts
    2,458

    Re: Deserialising a JSON array

    Quote Originally Posted by Bear89 View Post
    If I try to do that with my current declarations I can't reach the array elements. For example, I can retrieve:

    Code:
    memberNumber = responseObject.claimAssessment.claimant.currentMembership.memberNumber
    but

    Code:
    eventDate = responseObject.claimAssessment.medicalEvent.eventDate
    flags that eventDate is not a member of IEnumerable(Of JSONUtility.medicalEventPCResponse), presumably because it is inside the array?

    Are you thinking that I just try declaring the array elements without the IEnumerable and then loop? Because if I do that then I can define them, but the deserialize fails as it needs an IEnumerable ?

    I have also tried to deserialise the array alone, but the obvious syntaxes don’t allow me to do that, but is there a way to do that?
    Code:
    For each membership in responseObject.claimAssessment.claimant.currentMembership
        memberNumber = membership.memberNumber
    Or rather than declare the properties as IEnumerable(Of ...), you could try declaring them as a List(Of ...)

  5. #5
    Karen Payne MVP kareninstructor's Avatar
    Join Date
    Jun 2008
    Location
    Oregon
    Posts
    6,684

    Re: Deserialising a JSON array

    Wrote the following in C#, converted to VB.NET

    Code:
    Option Infer On
    
    Imports Microsoft.VisualBasic
    Imports System.Diagnostics
    Imports System.IO
    Imports Newtonsoft.Json
    
    Namespace ConsoleApp1
    	Friend Class Program
    		Shared Sub Main(ByVal args() As String)
    			Dim response = WebResponseMocked()
    
    			Debug.WriteLine($"    Status: {response.Status}")
    			Debug.WriteLine($"Assessment: {response.Assessment}")
    
    			For Each medicalEvent In response.Assessment.MedicalEvent
    
    				Debug.WriteLine($vbTab & "Event date: {medicalEvent.EventDate}")
    
    				For Each service In medicalEvent.Service
    					Debug.WriteLine($vbTab & vbTab & "assessmentCode: {service.AssessmentCode,-30}{service.Amount,-10}{service.Number,-5}{service.id}")
    
    					Debug.WriteLine($vbTab & vbTab & vbTab & "Code:{service.ErrorItem.Code,-5}, Reason: {service.ErrorItem.Reason}")
    				Next service
    
    				Debug.WriteLine("")
    			Next medicalEvent
    
    		End Sub
    
    		Private Shared Function WebResponseMocked() As PCIResponse
    			Dim response = JsonConvert.DeserializeObject(Of PCIResponse)(File.ReadAllText("response.json"))
    			Return response
    		End Function
    	End Class
    
    	Public Class PCIResponse
    		<JsonProperty("claimAssessment")>
    		Public Property Assessment() As Claimassessment
    		<JsonProperty("status")>
    		Public Property Status() As String
    	End Class
    
    	Public Class Claimassessment
    		<JsonProperty("medicalEvent")>
    		Public Property MedicalEvent() As Medicalevent()
    		Public Property claimId() As String
    	End Class
    
    
    	Public Class Medicalevent
    		<JsonProperty("service")>
    		Public Property Service() As Service()
    		<JsonProperty("eventDate")>
    		Public Property EventDate() As String
    		Public Property id() As String
    	End Class
    
    	Public Class Service
    		<JsonProperty("error")>
    		Public Property ErrorItem() As [Error]
    		Public Property id() As String
    		<JsonProperty("assessmentCode")>
    		Public Property AssessmentCode() As String
    		<JsonProperty("chargeAmount")>
    		Public Property Amount() As String
    		<JsonProperty("itemNumber")>
    		Public Property Number() As String
    	End Class
    
    	Public Class [Error]
    		<JsonProperty("code")>
    		Public Property Code() As Integer
    		<JsonProperty("text")>
    		Public Property Reason() As String
    	End Class
    End Namespace
    Code:
        Status: MEDICARE_REJECTED
    Assessment: ConsoleApp1.Claimassessment
    	Event date: 2022-04-16
    		assessmentCode: UNACCEPTABLE_ERROR            15600     110  A000
    			Code:9635 , Reason: Check Servicing Provider.  May not be able to provide the service for this item at date of service.
    
    	Event date: 2022-04-16
    		assessmentCode: UNACCEPTABLE_ERROR            78000     110  A001
    			Code:9635 , Reason: Check Servicing Provider.  May not be able to provide the service for this item at date of service.

  6. #6

    Thread Starter
    Lively Member
    Join Date
    Aug 2021
    Posts
    117

    Re: Deserialising a JSON array

    Excellent, thanks so much Karen and pd. In the end the List and other options didn't work pd as the need for deserialization and the need for full string to access each element were in conflict. However, your loop idea was essentially correct and Karen's suggestion of nesting the loops was perfect, and using essentially the same declarations as in my first post, and where resultPC is the Webservice response, the final vb is:
    Code:
                    Dim responseObject = JsonConvert.DeserializeObject(Of PCIResponse)(resultPC)
     
                    MsgBox($"Status: " & responseObject.status & vbCr)
                    If resultPC.Contains("memberNumber") Then
                        MsgBox("Medicare:  " & responseObject.claimAssessment.patient.currentMembership.memberNumber)
                    End If
    
                    For Each medicalEvent In responseObject.claimAssessment.medicalEvent
    
                        MsgBox("Event date:  " & medicalEvent.eventDate)
    
                        For Each service In medicalEvent.service
                            MsgBox("assessmentCode: " & service.assessmentCode & vbCr & "Amount:  " & service.chargeAmount & vbCr & "ItemNo:   " & service.itemNumber & vbCr & "Id:   " & service.id)
    
                            MsgBox("Code:  " & service.error.code & vbCr & "Reason: " & service.error.text)
                        Next service
    
                        'MsgBox("")
                    Next medicalEvent
    The ‘contains’ option allows for conditionally absent elements to be included.

    Thanks again both.
    Last edited by Bear89; May 10th, 2022 at 07:56 AM.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width