我需要将此URL下载到json,以便将其转换为对象。
不过,当我运行以下代码时,字符串返回为“”。
URL: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; }
}
}
答案 0 :(得分:1)
您应该反序列化为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")
答案 1 :(得分:1)
public static void Json()
{
string url = "https://data.ny.gov/resource/d6yy-54nr.json";
WebRequest request = WebRequest.Create(url);
WebResponse reply;
reply = request.GetResponse();
StreamReader returninfo = new StreamReader(reply.GetResponseStream());
string getinfo = returninfo.ReadToEnd();
List<Draw> Info = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Draw>>(getinfo);
foreach (var info in Info)
{
}
public class Draw
{
public DateTime draw_time { get; set; }
public string winning_numbers { get; set; }
public string multiplier { get; set; }
}
我这样尝试过,也许可以帮上忙。
答案 2 :(得分:0)
100%正确答案:
我错过了这一行代码:
ServicePointManager.SecurityProtocol = CType(3072, SecurityProtocolType)
最终代码:
Private Function DownloadAndSerializedJsonFromUrl(Of T As New)(ByVal url As String) As T
Using w = New WebClient()
Dim json_data = String.Empty
Try
ServicePointManager.SecurityProtocol = CType(3072, SecurityProtocolType)
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
字符串中不存在JSON数据,我可以使用JsonConver DeserializeObject方法将其转换!
谢谢大家!
有助于找到答案的文章: