2017-12-06 8 views
0

coinmarketcap.com의 API에서 json 응답을 변환하려고 할 때 오류가 발생합니다.
오류 :asp.net 형식 오류 개체를 캐스팅 할 수 없습니다

"타입의 객체 'System.Collections.Generic.List`1가 [으로 System.Object] 'System.Dynamic.ExpandoObject '를 입력 전송할 수 없습니다"

웹 클라이언트는 다른 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

는 매우 오랜 동안 VB.NET으로 작성,하지만 난 C#에서 당신을위한 해결책을 가지고하지 않았습니다. 명확하게 정의 된 객체 모델이 없다면 Json.Net을 사용하여 동적 객체로 파싱하는 것이 좋습니다. 우리는 API를 얻고 배열하고 있습니다. 그래서 Json.Net에 우리가 API를 파싱 할 것으로 기대한다고 말해야합니다. 아래는 나를위한 실용적인 솔루션입니다 (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; 
     } 
+0

내가 도와 줄 수있어서 기쁩니다! – mrkg