2021年11月17日 星期三

vb.net jsonconvert.deserializeobject dictionary

 

JSON -> Dictionaries:

Imports System.IO

Imports Newtonsoft.Json

Imports Newtonsoft.Json.Linq


Module Module1


    Sub Main()

        Dim json = File.ReadAllText("data.txt")


        Dim parsed = JsonConvert.DeserializeObject(Of Dictionary(Of String, Object))(json)


        Dim stringValue As String = parsed("string").ToString()

        Dim numberValue As Integer = CInt(parsed("number"))

        Dim arrayValue As JArray = parsed("array")

        Dim subObject As JObject = parsed("otherObject")


        Console.WriteLine("string: {0}", stringValue)

        Console.WriteLine("number: {0}", numberValue)


        Console.WriteLine("Array values:")

        For Each item As Object In arrayValue

            Console.WriteLine(item)

        Next


        Console.WriteLine("otherObject.number:")

        Console.WriteLine(CInt(subObject("number")))


    End Sub


End Module



JSON -> Classes:

Imports System.IO

Imports Newtonsoft.Json

Imports Newtonsoft.Json.Linq


Module Module1


    Sub Main()

        Dim json = File.ReadAllText("data.txt")


        Dim parsed = JsonConvert.DeserializeObject(Of ExampleData)(json)


        Console.WriteLine("number: {0}", parsed.Number)

        Console.WriteLine("string: {0}", parsed.String)


        Console.WriteLine("Array values:")

        For Each item As Integer In parsed.Array

            Console.WriteLine(item)

        Next


        Console.WriteLine("OtherObject.Number: {0}", parsed.OtherObject.Number)


    End Sub


End Module


Public Class ExampleData


    Public Property Number As Integer

    Public Property [String] As String

    Public Property Array As Integer()

    Public Property OtherObject As OtherObject


End Class


Public Class OtherObject


    Public Property Number As Integer


End Class


沒有留言:

張貼留言