VB - Newtonsoft.Json货币计划意外字符“{。”错误

时间:2017-12-05 15:08:43

标签: json vb.net api fixer.io

我正在尝试为学校项目建立一个基于api的在线货币计划。我做到了,但我正在尝试构建一个功能更强大的程序,所以我决定在我的程序中添加一个第二个窗体。第二种形式在过去的时间内进行货币兑换 。我在我的项目中使用的api可以这样做,所以可以这样做,但是当我尝试在字典中获取货币名称时,我会得到这样的错误:

  

'Newtonsoft.Json.JsonReaderException'türündebiryakalanamayanözeldurum,Newtonsoft.Json.dllöğesindeoluştu   解析值时遇到意外的字符:{。路径'费率',第1行,第43位。

这是我的代码:

Dim rawResp As String
        Dim request As HttpWebRequest
        Dim response As HttpWebResponse = Nothing
        Dim reader As StreamReader
        Dim jsonResultToDict As Dictionary(Of String, String)
        Dim kurlar As String
        Dim kur As Object
        Dim kurs As String
        request = DirectCast(WebRequest.Create("http://api.fixer.io/" + DateTimePicker1.Value.ToString("yyyy-MM-dd")), HttpWebRequest)
        response = DirectCast(request.GetResponse(), HttpWebResponse)
        reader = New StreamReader(response.GetResponseStream())
        rawResp = reader.ReadToEnd
        jsonResultToDict = JsonConvert.DeserializeObject(Of Dictionary(Of String, String))(rawResp)
        kurlar = jsonResultToDict.Item("rates")
        kur = JObject.Parse(kurlar)

顺便说一下,我还没有尝试在组合框中设置货币名称,因为我暂时无法获取数据。

这是api:http://fixer.io/

感谢您的帮助...

1 个答案:

答案 0 :(得分:0)

我认为因为"率"的json数据不适合您的字典模型"字符串,字符串",Newtonsoft JSON无法转换为" String,Single" (注意货币代码是如何用双引号而不是费率)。因此,您需要创建一个可以从JSON轻松转换的类对象。

例如,该类可能如下所示:

Public Class ForExRates Public base As String Public [date] As String 'enclose var in brackets; Date is a VB keyword. Public rates as Dictionary(Of String, Single)
Public Sub New() End Sub End Class

然后,将 Dictionary(Of String,String)的任何引用替换为 ForExRates

好的,所以你的代码应该如下:

    Dim rawResp As String
    Dim request As HttpWebRequest
    Dim response As HttpWebResponse = Nothing
    Dim reader As StreamReader
    Dim objForExRates As ForExRates

    request = DirectCast(WebRequest.Create("http://api.fixer.io/" + DateTimePicker1.Value.ToString("yyyy-MM-dd")), HttpWebRequest)
    response = DirectCast(request.GetResponse(), HttpWebResponse)
    reader = New StreamReader(response.GetResponseStream())
    rawResp = reader.ReadToEnd
    objForExRates = JsonConvert.DeserializeObject(Of ForExRates)(rawResp)
    Dim sCAD As String = "Rate for 'CAD': " + objForExRates.rates("CAD").ToString()