J86
J86

Reputation: 15237

How to parse the returned JSON and assign it some properties on an object in VB.Net?

In a VB.Net application (v4.0 of the .Net Framework) I am making a call to an API that returns the following:

{"CFResponse":{"AccountDetails":[{"AccountNum":"TEST","CurrentBalance":-58.24,"OriginalBalance":1530.01,"TotalPaid":215.33}]}}

I also have a variable (userInfo) holding an instance of GetUserInfoResult.vb that has a bunch of set properties from previous logic.

What is a clean way of getting the JSON data mapped to properties on my instance?

CurrentBalance > userInfo.Balances.CurrentBalance

OriginalBalance > userInfo.Balances.OriginalBalance

TotalPaid > userInfo.Balances.TotalPaid

Upvotes: 1

Views: 383

Answers (1)

A Friend
A Friend

Reputation: 2750

You'll need to make some changes but the rough idea is here

Private Sub SomeJsonThing()
    Dim json = "{'cFResponse': {'AccountDetails':[{'AccountNum':'TEST','CurrentBalance':-58.24,'OriginalBalance':1530.01,'TotalPaid':215.33}]}}"

    Dim tmpJObject As JObject = JsonConvert.DeserializeObject(json)
    Dim cfResponse As JToken = tmpJObject("CFResponse")
    Dim accDetails As JToken = cfResponse("AccountDetails")

    Dim accountDetailsList = accDetails.ToObject(Of List(Of AccountDetails))
    Dim accInfo = accountDetailsList.First

    userInfo.Balances.CurrentBalance = accInfo.CurrentBalance
    userInfo.Balances.OriginalBalance = accInfo.OriginalBalance
    userInfo.Balances.TotalPaid = accInfo.TotalPaid
End Sub

Public Class AccountDetails
    Property AccountNum As String
    Property CurrentBalance As Double
    Property OriginalBalance As Double
    Property TotalPaid As Double
End Class

I'd separate the JSON reading into a different method, and the setting of the properties as well.

Upvotes: 1

Related Questions