asp.net无法转换类型错误的对象

时间:2017-12-06 17:38:47

标签: c# asp.net json vb.net json.net

尝试从coinmarketcap.com的API转换json响应时出错 错误是:

  

"无法转换类型的对象   ' System.Collections.Generic.List`1 [System.Object的]'输入   ' System.Dynamic.ExpandoObject'"

Web客户端适用于其他API,但由于某些原因,不会填充硬币对象。任何对vb.net或c#中的修复的深入了解都会非常感激。

    Dim dt_results As DataTable, dr As DataRow, url As String = String.Empty, json As Object = Nothing, iCount As Integer = 0

    'temporarily store results
    dt_results = New DataTable
    dt_results.Columns.Add("name", GetType(String))
    dt_results.Columns.Add("symbol", GetType(String))
    dt_results.Columns.Add("price_usd", GetType(Double))

    Try
        url = "https://api.coinmarketcap.com/v1/ticker/?convert=usd&limit=10"
        Dim theurl As New Uri(url)

        Using webClient = New System.Net.WebClient()

            json = webClient.DownloadString(theurl)

            'create json object
            Dim converter = New ExpandoObjectConverter()
            Dim coin As Object = JsonConvert.DeserializeObject(Of ExpandoObject)(json, converter)

            For Each item In coin

                Dim name As String = coin(iCount).name
                Dim symbol As String = coin(iCount).symbol
                Dim price_usd As Double = coin(iCount).price_usd
                dr = dt_results.NewRow()
                dr("name") = name
                dr("symbol") = symbol
                dr("price_usd") = price_usd
                dt_results.Rows.Add(dr)
                iCount = iCount + 1
            Next
        End Using

    Catch ex As Exception
        Dim ts As String = ex.Message
        json = "1"
    End Try

工作解决方案......

        Dim d As JArray = JArray.Parse(json)

            For i As Integer = 0 To d.Count
                Dim name As String = d(i).Item("name")
                Dim symbol As String = d(i).Item("symbol")
                Dim price_usd As Double = CDbl(d(i).Item("price_usd"))
                dr = dt_results.NewRow()
                dr("name") = name
                dr("symbol") = symbol
                dr("price_usd") = price_usd
                dt_results.Rows.Add(dr)
                iCount = iCount + 1
            Next

1 个答案:

答案 0 :(得分:1)

Haven用VB.NET写了很长时间,但是我在C#中有一个解决方案。如果您没有明确定义的对象模型,我建议使用Json.Net,将其解析为动态对象。我们从API中获取和排列,所以我们需要告诉Json.Net我们希望它能够解析它。以下是我的工作解决方案(尽管在C#中)

using (WebClient cli = new WebClient())
        {
            string result = cli.DownloadString("https://api.coinmarketcap.com/v1/ticker/?convert=usd&limit=10");
            dynamic arrayFromApi = JArray.Parse(result);

            // Use however - presumably loop through items
            string s = arrayFromApi[0].name;
        }