Deserializing JSON in Visual basic

前端 未结 4 589
北荒
北荒 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:14

    Instead of needing to define a class, you can deserialize the JSON into an Object, like this:

    Dim json As String = "{""items"":[{""Name"":""John"",""Age"":""20"",""Gender"":""Male""},{""Name"":""Tom"",""Age"":""25"",""Gender"":""Male""},{""Name"":""Sally"",""Age"":""30"",""Gender"":""Female""}]}"
    
    Dim jss = New JavaScriptSerializer()
    Dim data = jss.Deserialize(Of Object)(json)
    

    Now, as an example, you could loop through the deserialized JSON and build an HTML table, like this:

    Dim sb As New StringBuilder()
    sb.Append("" & vbLf & "" & vbLf & "" & vbLf)
    
    ' Build the header based on the keys of the first data item.
    For Each key As String In data("items")(0).Keys
        sb.AppendFormat("" & vbLf, key)
    Next
    
    sb.Append("" & vbLf & "" & vbLf & "" & vbLf)
    
    For Each item As Dictionary(Of String, Object) In data("items")
        sb.Append("" & vbLf)
    
        For Each val As String In item.Values
            sb.AppendFormat("      " & vbLf, val)
        Next
    Next
    
    sb.Append("" & vbLf & "" & vbLf & "
    {0}
    {0}
    ") Dim myTable As String = sb.ToString()

    Disclaimer: I work with C# on a daily basis and this is a C# example using dynamic that was converted to VB.NET, please forgive me if there are any syntax errors with this.

提交回复
热议问题