Не удается декодировать файл JSON из Интернета в VB.NET - PullRequest
0 голосов
/ 31 мая 2019

У меня есть некоторый код ниже, который получает ответ от веб-сайта в порядке, мой код работает, пока он не доходит до бита декодирования, но не возвращает никаких объектов.Это моя первая попытка JSON и веб-связанных данных.

Работает нормально до: Dim dict As Object, который ничего не возвращает, я пробовал несколько альтернатив из Интернета, но я тупой.

Вот URL-адрес веб-сайта для JSON: https://www.metcheck.com/OTHER/json_data.asp?zipcode=wv12+4qz&locationID=60883&lat=52.6&lon=-2

Вот URL-адрес, на котором будет отображаться файл JSON: http://ws1.metcheck.com/ENGINE/v9_0/json.asp?lat=52.6&lon=-2&lid=60883&Fc=No

Imports System.IO
Imports System.Net
Imports System.Web.Script.Serialization

Public Class Weather
    Private Sub Weather_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Dim uriString As String = "http://ws1.metcheck.com/ENGINE/v9_0/json.asp?lat=52.6&lon=-2&lid=60883&Fc=No"
    Dim uri As New Uri(uriString)

    Dim request As HttpWebRequest = HttpWebRequest.Create(uri)
    request.Method = "GET"

    Dim response As HttpWebResponse = request.GetResponse()


    Dim read As New StreamReader(response.GetResponseStream())
    Dim raw As String = read.ReadToEnd

    Dim dict As Object = New JavaScriptSerializer().Deserialize(Of List(Of Object))(raw)

    For Each item As Object In dict
        TextBox1.Text = item("temperature").ToString & vbCrLf
        TextBox1.Text = item("dewpoint").ToString & vbCrLf
        TextBox1.Text = item("rain").ToString & vbCrLf
    Next


End Sub
End Class

Ответы [ 2 ]

0 голосов
/ 01 июня 2019

Настоящая проблема здесь заключается в том, что вы пытаетесь десериализовать в список, но ваш JSON фактически представляет один объект, содержащий свойство данных, которое затем содержит список объектов.Вот почему вы получаете эту ошибку.Json.Net не может десериализовать отдельный объект в список.Я думаю, что вы действительно хотите сделать, это определить класс контейнера

Public Class Metdata
    Public Property myDictionary As List(Of Dictionary(Of String, Object))
End Class

И тогда ваша подпрограмма будет выглядеть так:

    Private Sub Weather_Load(sender As Object, e As EventArgs) 'Handles MyBase.Load
    Dim uriString As String = "http://ws1.metcheck.com/ENGINE/v9_0/json.asp?lat=52.6&lon=-2&lid=60883&Fc=No"
    Dim uri As New Uri(uriString)

    Dim request As HttpWebRequest = HttpWebRequest.Create(uri)
    request.Method = "GET"

    Dim response As HttpWebResponse = request.GetResponse()


    Dim read As New StreamReader(response.GetResponseStream())
    Dim raw As String = read.ReadToEnd

    Dim dict As Metdata
    dict = JsonConvert.DeserializeObject(Of Metdata)(raw)


End Sub

Partial Public Class Metdata
    Public Property myDictionary As List(Of Dictionary(Of String, Object))
End Class
Public Class Forecast

        <JsonProperty("temperature")>
        Public Property Temperature As String

        <JsonProperty("dewpoint")>
        Public Property Dewpoint As String

        <JsonProperty("rain")>
        Public Property Rain As String

        <JsonProperty("freezinglevel")>
        Public Property Freezinglevel As String

        <JsonProperty("uvIndex")>
        Public Property UvIndex As String

        <JsonProperty("totalcloud")>
        Public Property Totalcloud As String

        <JsonProperty("lowcloud")>
        Public Property Lowcloud As String

        <JsonProperty("medcloud")>
        Public Property Medcloud As String

        <JsonProperty("highcloud")>
        Public Property Highcloud As String

        <JsonProperty("humidity")>
        Public Property Humidity As String

        <JsonProperty("windspeed")>
        Public Property Windspeed As String

        <JsonProperty("meansealevelpressure")>
        Public Property Meansealevelpressure As String

        <JsonProperty("windgustspeed")>
        Public Property Windgustspeed As String

        <JsonProperty("winddirection")>
        Public Property Winddirection As String

        <JsonProperty("windletter")>
        Public Property Windletter As String

        <JsonProperty("icon")>
        Public Property Icon As String

        <JsonProperty("iconName")>
        Public Property IconName As String

        <JsonProperty("chanceofrain")>
        Public Property Chanceofrain As String

        <JsonProperty("chanceofsnow")>
        Public Property Chanceofsnow As String

        <JsonProperty("dayOfWeek")>
        Public Property DayOfWeek As String

        <JsonProperty("weekday")>
        Public Property Weekday As String

        <JsonProperty("sunrise")>
        Public Property Sunrise As String

        <JsonProperty("sunset")>
        Public Property Sunset As String

        <JsonProperty("dayOrNight")>
        Public Property DayOrNight As String

        <JsonProperty("utcTime")>
        Public Property UtcTime As DateTime
    End Class

Public Class ForecastLocation

    <JsonProperty("forecast")>
    Public Property Forecast As Forecast()

    <JsonProperty("continent")>
    Public Property Continent As String

    <JsonProperty("country")>
    Public Property Country As String

    <JsonProperty("location")>
    Public Property Location As String

    <JsonProperty("latitude")>
    Public Property Latitude As Double

    <JsonProperty("longitude")>
    Public Property Longitude As Double

    <JsonProperty("timezone")>
    Public Property Timezone As Integer
End Class

Public Class MetcheckData

    <JsonProperty("forecastLocation")>
    Public Property ForecastLocation As ForecastLocation
End Class

Public Class Metdata

    <JsonProperty("metcheckData")>
    Public Property MetcheckData As MetcheckData

    <JsonProperty("feedCreation")>
    Public Property FeedCreation As DateTime

    <JsonProperty("feedCreator")>
    Public Property FeedCreator As String

    <JsonProperty("feedModel")>
    Public Property FeedModel As String

    <JsonProperty("feedModelRun")>
    Public Property FeedModelRun As String

    <JsonProperty("feedModelRunInitialTime")>
    Public Property FeedModelRunInitialTime As DateTime

    <JsonProperty("feedResolution")>
    Public Property FeedResolution As String
End Class

dict.Metcheckdata.Forecastlocation.Forecast будет содержать ваши 155записи.

0 голосов
/ 31 мая 2019

Я раньше не работал с JavaScriptSerializer, но это может быть из-за того, что вы пытаетесь десериализовать список (объекта) вместо более конкретного типа. Если вы добавляете серию классов, соответствующих структуре JSON:

Public Class Rootobject
    Public Property metcheckData As Metcheckdata
    Public Property feedCreation As Date
    Public Property feedCreator As String
    Public Property feedModel As String
    Public Property feedModelRun As String
    Public Property feedModelRunInitialTime As Date
    Public Property feedResolution As String
End Class

Public Class Metcheckdata
    Public Property forecastLocation As Forecastlocation
End Class

Public Class Forecastlocation
    Public Property forecast As List(Of Forecast)
    Public Property continent As String
    Public Property country As String
    Public Property location As String
    Public Property latitude As Single
    Public Property longitude As Single
    Public Property timezone As Integer
End Class

Public Class Forecast
    Public Property temperature As String
    Public Property dewpoint As String
    Public Property rain As String
    Public Property freezinglevel As String
    Public Property uvIndex As String
    Public Property totalcloud As String
    Public Property lowcloud As String
    Public Property medcloud As String
    Public Property highcloud As String
    Public Property humidity As String
    Public Property windspeed As String
    Public Property meansealevelpressure As String
    Public Property windgustspeed As String
    Public Property winddirection As String
    Public Property windletter As String
    Public Property icon As String
    Public Property iconName As String
    Public Property chanceofrain As String
    Public Property chanceofsnow As String
    Public Property dayOfWeek As String
    Public Property weekday As String
    Public Property sunrise As String
    Public Property sunset As String
    Public Property dayOrNight As String
    Public Property utcTime As Date
End Class

А затем попытайтесь десериализовать следующим образом:

Dim dict As Object = New JavaScriptSerializer().Deserialize(Of Rootobject)(raw)

Это работает как положено?

...