Deserializing JSON in Visual basic

前端 未结 4 590
北荒
北荒 2020-11-29 10:26

Basically, I\'m trying to parse the comments from a 4chan thread using the 4chan JSON API. https://github.com/4chan/4chan-API

basically, there is one rich text box c

4条回答
  •  不知归路
    2020-11-29 11:04

    Since you're importing Newtonsoft.Json, you can just use the JsonConvert.DeserializeObject(String) method:

    Dim exampleJson As String = "{ 'no':'123', 'name':'Some Name', 'com':'This is a comment'}"
    Dim post As Post = JsonConvert.DeserializeObject(Of Post)(exampleJson)
    Dim com As String = post.com
    post_text_box.Text = com
    

    Alternatively, if you don't want to create a class for Post, you can use JsonConvert.DeserializeAnonymousType(String, T):

    Dim exampleJson As String = "{ 'no':'123', 'name':'Some Name', 'com':'This is a comment'}"
    Dim tempPost = New With {Key .com = ""}
    Dim post = JsonConvert.DeserializeAnonymousType(exampleJson, tempPost)
    Dim com As String = post.com
    post_text_box.Text = com
    

    EDIT: It looks like you're getting an array back from the API:

    {
        "posts" : [{
                "no" : 38161812,
                "now" : "11\/19\/13(Tue)15:18",
                "name" : "Anonymous",
                "com" : ‌​ "testing thread for JSON stuff",
                "filename" : "a4c",
                "ext" : ".png",
                "w" : 386,
                "h" : 378,
                "tn_w" : 250,
                "tn_h" : 244,
                "tim" ‌​ : 1384892303386,
                "time" : 1384892303,
                "md5" : "tig\/aNmBqB+zOZY5upx1Fw==",
                "fsize" : 6234,
                "‌​resto" : 0,
                "bumplimit" : 0,
                "imagelimit" : 0,
                "replies" : 0,
                "images" : 0
            }
        ]
    }
    

    In that case, you will need to change the type that is being deserialized to Post():

    First, add another small wrapper class:

    Public Class PostWrapper
        Public posts() As Post
    End Class
    

    Then adjust your deserialization code:

    Dim json As String = input_box.Text
    Dim postWrapper = JsonConvert.DeserializeObject(Of PostWrapper)(json) ' Deserialize array of Post objects
    Dim posts = postWrapper.posts
    
    If posts.Length = 1 Then ' or whatever condition you prefer
        post_text_box.Text = posts(0).com
    End If
    

提交回复
热议问题