我想从Json响应中读取数据,但我很难获得数据。我想从Json响应中读取这个项目,如下所示
period, fromDate, dueDate, totalInstallmentAmountForPeriod
Json响应
{
"currency": {
"decimalPlaces": 0,
"inMultiplesOf": 1
},
"loanTermInDays": 92,
"totalPrincipalDisbursed": 100000,
"periods": [
{
"dueDate": [
2022,
7,
8
],
"principalDisbursed": 100000,
"totalActualCostOfLoanForPeriod": 0
},
{
"period": 1,
"fromDate": [
2022,
7,
8
],
"dueDate": [
2022,
8,
8
],
"daysInPeriod": 31,
"totalInstallmentAmountForPeriod": 36035
},
{
"period": 2,
"fromDate": [
2022,
8,
8
],
"dueDate": [
2022,
9,
8
],
"daysInPeriod": 31,
"totalInstallmentAmountForPeriod": 36035
}
],
"mandatorySavings": [
{ "periodId": 0"expectedSavings": 10000.000}]
}
你的JSON是无效的,它看起来像有一个缺失的逗号在mandatoryssaving ->periodId和expectedSavings.
Visual Studio有一个很酷的功能,叫做将JSON粘贴为类,可以在Edit>膏体专用>将JSON粘贴为类。使用Newtonsoft。Json或System.Text。Json中,你可以使用装饰器来整理类,这样你就可以符合。net标准的命名约定,同时仍然将Json序列化为预期的值。我也更喜欢使用IEnumerables而不是数组,但是将JSON粘贴为类使用后者。
这是类定义的整理方式:
Public Class Rootobject
<JsonProperty("currency")>
Public Property Currency As Currency
<JsonProperty("loanTermInDays")>
Public Property LoanTermInDays As Integer
<JsonProperty("totalPrincipalDisbursed")>
Public Property TotalPrincipalDisbursed As Integer
<JsonProperty("periods")>
Public Property Periods As IEnumerable(Of Period)
<JsonProperty("mandatorySavings")>
Public Property MandatorySavings As IEnumerable(Of Mandatorysaving)
End Class
Public Class Currency
<JsonProperty("decimalPlaces")>
Public Property DecimalPlaces As Integer
<JsonProperty("inMultiplesOf")>
Public Property InMultiplesOf As Integer
End Class
Public Class Period
<JsonProperty("dueDate")>
Public Property DueDate As IEnumerable(Of Integer)
<JsonProperty("principalDisbursed")>
Public Property PrincipalDisbursed As Integer
<JsonProperty("totalActualCostOfLoanForPeriod")>
Public Property TotalActualCostOfLoanForPeriod As Integer
<JsonProperty("period")>
Public Property Period As Integer
<JsonProperty("fromDate")>
Public Property FromDate As IEnumerable(Of Integer)
<JsonProperty("daysInPeriod")>
Public Property DaysInPeriod As Integer
<JsonProperty("totalInstallmentAmountForPeriod")>
Public Property TotalInstallmentAmountForPeriod As Integer
End Class
Public Class Mandatorysaving
<JsonProperty("periodId")>
Public Property PeriodId As Integer
<JsonProperty("expectedSavings")>
Public Property ExpectedSavings As Integer
End Class
现在你需要做的就是使用JsonConvert。DeserializeObject将JSON文字转换为Rootobject类的实例:
Dim conversion = JsonConvert.DeserializeObject(Of Rootobject)(literal)
小提琴:https://dotnetfiddle.net/Eq88rV