json - VB.net 中 json.net 的简单工作示例

标签 json vb.net serialization json.net

我有以下来自提供者的简化 JSON 字符串,自从我使用 Visual Studio 和 vb.Net 已经很长时间了,所以我很生疏!

{
"Venue": {
    "ID": 3145,
    "Name": "Big Venue, Clapton",
    "NameWithTown": "Big Venue, Clapton, London",
    "NameWithDestination": "Big Venue, Clapton, London",
    "ListingType": "A",
    "Address": {
        "Address1": "Clapton Raod",
        "Address2": "",
        "Town": "Clapton",
        "County": "Greater London",
        "Postcode": "PO1 1ST",
        "Country": "United Kingdom",
        "Region": "Europe"
    },
    "ResponseStatus": {
        "ErrorCode": "200",
        "Message": "OK"
    }
}
}

我想使用 JSON.Net 把它变成我可以使用的东西,我已经阅读了示例等,JSON.net 看起来像答案,但我无处可去。

我的 .Net 代码(Me.TextBox1.Text 包含上面显示的 JSON)
Imports Newtonsoft.Json

Public Class Form1

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim obj As JSON_result
    obj = JsonConvert.DeserializeObject(Of JSON_result)(Me.TextBox1.Text)

    MsgBox(obj.ID)
End Sub
End Class

Public Class JSON_result
    Public ID As Integer
    Public Name As String
    Public NameWithTown As String
    Public NameWithDestination As String
    Public ListingType As String
 End Class

有人可以解释为什么 obj.ID 总是以 0 结束,为什么我的类的其他属性都没有被填充,以及我需要做什么来解决这个问题,没有报告错误。

最佳答案

您的类(class) JSON_result与您的 JSON 字符串不匹配。注意对象 JSON_result将代表被包裹在另一个名为 "Venue" 的属性中.

所以要么为此创建一个类,例如:

Public Class Container
    Public Venue As JSON_result
End Class

Public Class JSON_result
    Public ID As Integer
    Public Name As String
    Public NameWithTown As String
    Public NameWithDestination As String
    Public ListingType As String
End Class

Dim obj = JsonConvert.DeserializeObject(Of Container)(...your_json...)

或将您的 JSON 字符串更改为
{
    "ID": 3145,
    "Name": "Big Venue, Clapton",
    "NameWithTown": "Big Venue, Clapton, London",
    "NameWithDestination": "Big Venue, Clapton, London",
    "ListingType": "A",
    "Address": {
        "Address1": "Clapton Raod",
        "Address2": "",
        "Town": "Clapton",
        "County": "Greater London",
        "Postcode": "PO1 1ST",
        "Country": "United Kingdom",
        "Region": "Europe"
    },
    "ResponseStatus": {
        "ErrorCode": "200",
        "Message": "OK"
    }
}

或使用例如ContractResolver解析 JSON 字符串。

关于json - VB.net 中 json.net 的简单工作示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21676708/

相关文章:

WPF 和 MVVM : Any examples using VB. 网络?

c# - 如何将图像 url 转换为 system.drawing.image

java - Jackson - 将 ZonedDateTime 序列化为 ISO 8601 字符串

java - 简单框架 XML 反序列化 ValueRequiredException

c# - 如何在 Web API 2.2 中序列化 IdentityUser 引用?

java - 递归合并 JSON 结构

javascript - AngularJS (1.5.8) - 如何直接从获取 json 对象的 Controller 内填充选择选项列表?

json - 我应该如何从 bradjasper 的 django-jsonfield 升级到 Django 的内置 jsonfield?

java - 陷入解析 JSON 的困境

c# - 在字符串而不是字符上拆分字符串