【问题标题】:Trying To Deserialize JSON Dictionairy Using Objects尝试使用对象反序列化 JSON 字典
【发布时间】:2019-01-06 21:20:12
【问题描述】:

作为标准,我创建了一个 Web 请求并接收 JSON 格式的响应。我正在尝试使用 JSON.NET 反序列化这个 JSON(不过我认为我不需要这个)。

我尝试过使用以下代码,但是我不完全确定如何使对象实际包含一些数据。运行此代码时,我收到一条错误消息,显示我的 JObject“当前”为“无”。

Imports System.Net
Imports System.IO
Imports Newtonsoft.Json.Linq
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
  ServicePointManager.Expect100Continue = True
  ServicePointManager.SecurityProtocol = CType(3072, SecurityProtocolType)
  ServicePointManager.DefaultConnectionLimit = 9999
  Dim uriString As String = "https://dev.tescolabs.com/grocery/products/?query=chicken&offset=0&limit=2"
  Dim uri As New Uri(uriString)

  Dim r As HttpWebRequest = HttpWebRequest.Create(uri)
  r.Headers("Ocp-Apim-Subscription-Key") = "xxxxxxxxxxxxxxxxxxxxxxxxxxxx"
  r.Method = "GET"
  r.Proxy = Nothing
  Dim re As HttpWebResponse = r.GetResponse()

  Dim read As New StreamReader(re.GetResponseStream())
  Dim raw As String = read.ReadToEnd()
  Dim a As JObject = JObject.Parse(raw)
  Dim current As JObject = DirectCast(a("image"), JObject)
  MessageBox.Show(current("image"))
End Sub
End Class
Public Class Totals
  Public Property all As Integer
  Public Property _new As Integer
  Public Property offer As Integer
End Class

Public Class Result
  Public Property image As String
  Public Property superDepartment As String
  Public Property tpnb As Integer
  Public Property ContentsMeasureType As String
  Public Property name As String
  Public Property UnitOfSale As Integer
  Public Property description() As String
  Public Property AverageSellingUnitWeight As Single
  Public Property UnitQuantity As String
  Public Property id As Integer
  Public Property ContentsQuantity As Single
  Public Property department As String
  Public Property price As Single
  Public Property unitprice As Single
End Class

因此,在 textbox1 中,应该是每个产品,包括每个产品的所有信息。提取完所有这些信息后,我最终想将每个产品的信息添加到 datagridview 中,以更清晰的方式呈现信息。但是,我无法通过这个阶段。

我现在已经尝试了以下代码:

Dim results = Newtonsoft.Json.JsonConvert.DeserializeObject(Of Result)(raw) 
    For Each image In results.image
        TextBox1.Text = "Image URL:" + results.image
    Next

我收到的 JSON 作为响应:

{
  "uk" : {
    "ghs" : {
      "products" : {
        "input_query" : "chicken",
        "output_query" : "chicken",
        "filters" : { },
        "queryPhase" : "primary",
        "totals" : {
          "all" : 1358,
          "new" : 9,
          "offer" : 478
        },
        "config" : "default",
        "results" : [ {
          "image" : "http://img.tesco.com/Groceries/pi/325/5057008546325/IDShot_90x90.jpg",
          "superDepartment" : "Fresh Food",
          "tpnb" : 81866107,
          "ContentsMeasureType" : "G",
          "name" : "Tesco British Chicken Breast Portions 650G",
          "UnitOfSale" : 1,
          "description" : [ "Fresh class A skinless chicken breast fillet portions."],
          "AverageSellingUnitWeight" : 0.746,
          "UnitQuantity" : "KG",
          "id" : 294007923,
          "ContentsQuantity" : 650,
          "department" : "Fresh Meat & Poultry",
          "price" : 3.8,
          "unitprice" : 5.85
        }, {
          "image" : "http://img.tesco.com/Groceries/pi/531/5054775703531/IDShot_90x90.jpg",
          "superDepartment" : "Fresh Food",
          "tpnb" : 64083120,
          "ContentsMeasureType" : "KG",
          "name" : "Tesco British Large Whole Chicken 1.55-1.95Kg",
          "UnitOfSale" : 1,
          "AverageSellingUnitWeight" : 1.785,
          "description" : [ "Fresh Class A whole chicken without giblets."],
          "UnitQuantity" : "KG",
          "id" : 292276232,
          "ContentsQuantity" : 1.75,
          "department" : "Fresh Meat & Poultry",
          "price" : 3.5,
          "unitprice" : 2.0
        } ],
        "suggestions" : [ ]
      }
    }
  }
}

但是我仍然没有在 textbox1 中收到图像 URL,并且不知道为什么。任何帮助将不胜感激。

【问题讨论】:

    标签: json vb.net json.net


    【解决方案1】:

    我从未使用过JSON.NETNEWTONSOFT,我倾向于只使用 JSON 的一些东西,我通常只使用“内置”方法。

    您的结果在一个数组中,这可能是您的第一个问题。那么您的For Each 看起来似乎走上了正轨,但不确定results 是否被正确引用?

    无论如何...

    他是一个工作示例,希望能有所帮助。

    我刚刚做了一个简单的 WinForm 并添加了一个button。 我添加了一个参考:System.Web.Extensions

    试试下面的代码:(让我知道你是怎么做到的)

    Imports System.Web.Script.Serialization
    
    Public Class Form1
        Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    
            'This is just my JSON source I used for testing. (The JSON response you posted)
            Dim raw As String = IO.File.ReadAllText("C:\MEDIA\json_test.json")
    
            'This should now be the same as your: Dim raw As String = read.ReadToEnd()
            'From here on, try this:
    
            'Deserialise
            Dim ser As JavaScriptSerializer = New JavaScriptSerializer()
            Dim Tesco As JSON = New JSON
            Tesco = ser.Deserialize(Of JSON)(raw)
    
            'Loop through results and print each image URL
            For Each r As Result In Tesco.uk.ghs.products.results
                Console.WriteLine("Image URL:" & r.image)
            Next
        End Sub
    End Class
    
    Public Class Totals
        Public Property all As Integer
        Public Property [new] As Integer
        Public Property offer As Integer
    End Class
    
    Public Class Result
        Public Property image As String
        Public Property superDepartment As String
        Public Property tpnb As Integer
        Public Property ContentsMeasureType As String
        Public Property name As String
        Public Property UnitOfSale As Integer
        Public Property description As String()
        Public Property AverageSellingUnitWeight As Double
        Public Property UnitQuantity As String
        Public Property id As Integer
        Public Property ContentsQuantity As Double
        Public Property department As String
        Public Property price As Double
        Public Property unitprice As Double
    End Class
    
    Public Class Products
        Public Property input_query As String
        Public Property output_query As String
        Public Property queryPhase As String
        Public Property totals As Totals
        Public Property config As String
        Public Property results As Result()
        Public Property suggestions As Object()
    End Class
    
    Public Class Ghs
        Public Property products As Products
    End Class
    
    Public Class Uk
        Public Property ghs As Ghs
    End Class
    
    Public Class JSON
        Public Property uk As Uk
    End Class
    

    【讨论】:

    • 完美运行!一开始我很着迷,我认为这不可能自然而然,我需要使用 JSON.NET。我的 FOR 循环的语法也很有趣。非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多