如何解析返回的JSON并在VB.Net?

时间:2017-09-06 07:39:18

标签: asp.net json vb.net

在VB.Net应用程序(.Net Framework的v4.0)中,我正在调用返回以下内容的API:

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

我还有一个变量(userInfo),其中包含GetUserInfoResult.vb的实例,该实例具有来自先前逻辑的一组设置属性。

什么是将JSON数据映射到我的实例上的属性的简洁方法?

CurrentBalance> userInfo.Balances.CurrentBalance

OriginalBalance> userInfo.Balances.OriginalBalance

TotalPaid> userInfo.Balances.TotalPaid

1 个答案:

答案 0 :(得分:1)

你需要做一些改变,但粗略的想法就在这里

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

我将JSON读数分成不同的方法,以及属性的设置。