首页 > 解决方案 > 将 .json 文件从 URL 下载到对象

问题描述

我需要将此 URL 下载到 json,以便将其转换为对象。

但是,当我运行以下代码时,字符串返回为“”。

网址:https ://data.ny.gov/resource/d6yy-54nr.json

我究竟做错了什么?

注意:代码在 VB.net 中,对象在 C# 中(这无关紧要)

    Protected Sub btnProcess_Click(sender As Object, e As EventArgs)
        Try
            Dim result = DownloadAndSerializedJsonFromUrl(Of a27baseball.Common.Objects.Oreo.DownloadJsonPowerball)("https://data.ny.gov/resource/5xaw-6ayf.json")
        Catch ex As Exception
            Response.Write(ex.ToString())
        End Try
    End Sub

    Private Function DownloadAndSerializedJsonFromUrl(Of T As New)(ByVal url As String) As T
        Using w = New WebClient()
            Dim json_data = String.Empty

            Try
                json_data = w.DownloadString(url)
            Catch __unusedException1__ As Exception
                Response.Write(__unusedException1__.ToString())
            End Try

            Return If(Not String.IsNullOrEmpty(json_data), JsonConvert.DeserializeObject(Of T)(json_data), New T())
        End Using
    End Function
namespace a27baseball.Common.Objects.Oreo
{
    public class DownloadJsonPowerball
    {
        public string draw_date { get; set; }

        public string winning_numbers { get; set; }

        public string multiplier { get; set; }
    }
}

标签: c#json

解决方案


您应该反序列化为List<a27baseball.Common.Objects.Oreo.DownloadJsonPowerball>类型而不是a27baseball.Common.Objects.Oreo.DownloadJsonPowerball类型。由于 json 文件内容包含您的对象类型的数组。

 Dim result = DownloadAndSerializedJsonFromUrl(Of List(Of a27baseball.Common.Objects.Oreo.DownloadJsonPowerball))("https://data.ny.gov/resource/5xaw-6ayf.json")

推荐阅读