尝试使用对象反序列化JSON Dictionairy

时间:2019-01-06 21:20:13

标签: json vb.net json.net

作为标准,我已经创建了一个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,也不知道为什么。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分: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