使用 JSON.NET VB.NET 解析 JSON



我正在尝试使用 JSON.NET 解析一些JSON;但是,这不是我熟悉的东西,我正在努力反序列化它。

这是 JSON:

{
"disclaimer": "use at own risk",
"license": "testing",
"timestamp": 1391770861,
"base": "USD",
"rates": {
"AED": 3.672839,
"AFN": 56.367,
"ALL": 103.5113,
"AMD": 412.35,
"ANG": 1.78894,
"AOA": 97.608324,
"ARS": 7.880804,
"AUD": 1.117779,
"AWG": 1.789825,
"AZN": 0.784133,
"BAM": 1.442736,
"BBD": 2
}
}

这是我目前的代码:

Public Sub ParseJSON()
JSONResponse = String.Empty
Dim request As HttpWebRequest = DirectCast(HttpWebRequest.Create(LatestURL), HttpWebRequest)
request.ContentType = "application/json; charset=utf-8"
request.Accept = "application/json, text/javascript, */*"
request.Method = "POST"
Using writer As New StreamWriter(request.GetRequestStream())
writer.Write("{id : 'test'}")
End Using
Dim response As WebResponse = request.GetResponse()
Dim stream As Stream = response.GetResponseStream()
Using StreamReader As New StreamReader(stream)
While Not StreamReader.EndOfStream
JSONResponse += StreamReader.ReadLine()
End While
End Using
Dim RateReply = JsonConvert.DeserializeObject(Of RateReply)(JSONResponse)
End Sub
Public Class RateReply
Public rates As IList(Of Rate)
Public base As String
Public timeStamp As Integer
Public license As String
Public disclaimer As String
Public Sub New()
rates = New List(Of Rate)()
End Sub
End Class
Public Class Rate
Public Currency As String
Public Rate As Decimal
End Class

我目前得到的异常是:

Newtonsoft.Json.JsonSerializationException:无法将当前 JSON 对象(例如 {"name":"value"})反序列化为类型"System.Collections.Generic.IList"1[KTMOM.Tests.Rate]',因为该类型需要一个 JSON 数组(例如 [1,2,3])才能正确反序列化。 若要修复此错误,请将 JSON 更改为 JSON 数组(例如 [1,2,3])或更改反序列化类型,使其是可以从 JSON 对象反序列化的普通 .NET 类型(例如,不是整数等基元类型,也不是数组或列表等集合类型)。还可以将 JsonObjectAttribute 添加到类型中,以强制它从 JSON 对象反序列化。

我相信这是因为速率未在 JSON 中定义为数组,但是,我不知道如何解决这个问题。

任何帮助将不胜感激。

要解决此问题,您需要更改 JSON 格式以按照错误消息的建议返回数组,或者如果无法定义另一个类来表示Rates

Public Class Rates
Public AED As Double
.....
.....
Public BBD As Double
End Class

然后将类RateReplayrates字段定义为Rates

Public rates As Rates

您可以使用

暗率作为字典(字符串,双精度)

相关内容

  • 没有找到相关文章

最新更新