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

时间:2014-02-10 12:02:37

标签: 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,为什么我的类的其他任何属性都没有填充,我需要做些什么来解决这个问题,没有报告错误。

3 个答案:

答案 0 :(得分:27)

您的班级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字符串。

答案 1 :(得分:19)

Imports Newtonsoft.Json.Linq

Dim json As JObject = JObject.Parse(Me.TextBox1.Text)
MsgBox(json.SelectToken("Venue").SelectToken("ID"))

答案 2 :(得分:0)

代替此

yarn build

您也可以使用


$ sh scripts/copy-build.sh
mkdir: ../../target/classes: No such file or directory
✅  Copying resources from ../build to ../../target/classes/public
usage: cp [-R [-H | -L | -P]] [-fi | -n] [-apvXc] source_file target_file
       cp [-R [-H | -L | -P]] [-fi | -n] [-apvXc] source_file ... target_directory
error Command failed with exit code 64.