Code development platform for open source projects from the European Union institutions

Skip to content
Snippets Groups Projects
cJSONparser.vb 11.2 KiB
Newer Older
Terry Burns's avatar
Terry Burns committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429
' Copyright 2014 European Union.
' Licensed under the EUPL (the 'Licence');
'
' * You may not use this work except in compliance with the Licence.
' * You may obtain a copy of the Licence at: http://ec.europa.eu/idabc/eupl
' * Unless required by applicable law or agreed to in writing,
'   software distributed under the Licence is distributed on an "AS IS" basis,
'   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
'
' See the LICENSE.txt for the specific language governing permissions and limitations.
Imports System.Collections.Generic
Imports Newtonsoft.Json


'uses JSON.NET http://json.codeplex.com/

Public Class cJSON
    Public Content As Dictionary(Of String, Object)
    Public ErrorMsg As String

    Public Sub New()
        Content = New Dictionary(Of String, Object)
    End Sub


    Public Function ReadFile(ByVal path As String) As Boolean
        Dim file As Microsoft.VisualBasic.FileIO.TextFieldParser
        Dim str As String


        Content.Clear()

        'check if file exists
        If Not IO.File.Exists(path) Then
            ErrorMsg = "file not found"
            Return False
        End If

        'open file
        Try
            file = New Microsoft.VisualBasic.FileIO.TextFieldParser(path)
        Catch ex As Exception
            ErrorMsg = ex.Message
            Return False
        End Try

        'Check if file is empty
        If file.EndOfData Then
            file.Close()
            ErrorMsg = "file is empty"
            Return False
        End If

        'read file
        str = file.ReadToEnd

        'close file
        file.Close()

        'parse JSON to Dictionary
        Try
            'JSONobj = JsonConvert.DeserializeObject(str)
            Content = JsonConvert.DeserializeObject(str, Content.GetType)
        Catch ex As Exception
            ErrorMsg = ex.Message
            Return False
        End Try

        Return True

    End Function

    Public Function WriteFile(ByVal path As String) As Boolean
        Dim file As System.IO.StreamWriter
        Dim str As String
        Dim First As Boolean = True

        If Content.Count = 0 Then Return False

        Try
            str = Newtonsoft.Json.JsonConvert.SerializeObject(Content, Formatting.Indented)
            file = My.Computer.FileSystem.OpenTextFileWriter(path, False)
        Catch ex As Exception
            Return False
        End Try

        file.Write(str)

        file.Close()

        Return True

    End Function


#Region "old self-made parser"
    Private fullfile As String

    Private Function ReadFileXXX(ByVal path As String) As Boolean
        Dim file As Microsoft.VisualBasic.FileIO.TextFieldParser

        Content.Clear()

        'check if file exists
        If Not IO.File.Exists(path) Then Return False

        'open file
        Try
            file = New Microsoft.VisualBasic.FileIO.TextFieldParser(path)
        Catch ex As Exception
            Return False
        End Try

        'Check if file is empty
        If file.EndOfData Then
            file.Close()
            Return False
        End If

        'read file
        fullfile = file.ReadToEnd

        'close file
        file.Close()

        'trim spaces
        fullfile = fullfile.Trim

        'remove line breaks
        fullfile = fullfile.Replace(vbCrLf, "")

        If Left(fullfile, 1) <> "{" Or Right(fullfile, 1) <> "}" Then Return False

        'parse JSON to Dictionary
        Try
            Content = GetObject()
        Catch ex As Exception
            Return False
        End Try


        Return True

    End Function




    Private Function WriteFileXXX(ByVal path As String) As Boolean
        Dim file As System.IO.StreamWriter
        Dim kv As KeyValuePair(Of String, Object)
        Dim str As New System.Text.StringBuilder
        Dim First As Boolean = True

        If Content.Count = 0 Then Return False

        Try
            str.AppendLine("{")
            For Each kv In Content
                If First Then
                    First = False
                Else
                    str.AppendLine(",")
                End If
                str.Append(GetKeyValString(1, kv))
            Next
            str.AppendLine()
            str.AppendLine("}")
        Catch ex As Exception
            Return False
        End Try

        Try
            file = My.Computer.FileSystem.OpenTextFileWriter(path, False)
        Catch ex As Exception
            Return False
        End Try

        file.Write(str.ToString)

        file.Close()

        Return True

    End Function

    Private Function GetKeyValString(ByVal TabLvl As Integer, ByRef kv As KeyValuePair(Of String, Object)) As String
        Dim str As New System.Text.StringBuilder
        Dim obj As Object
        Dim kv0 As KeyValuePair(Of String, Object)
        Dim First As Boolean

        str.Append(Tabs(TabLvl) & ChrW(34) & kv.Key & ChrW(34) & ": ")

        Select Case kv.Value.GetType

            Case GetType(Dictionary(Of String, Object))

                str.AppendLine("{")

                First = True
                For Each kv0 In kv.Value
                    If First Then
                        First = False
                    Else
                        str.AppendLine(",")
                    End If
                    str.Append(GetKeyValString(TabLvl + 1, kv0))
                Next

                str.AppendLine()
                str.Append(Tabs(TabLvl) & "}")

            Case GetType(List(Of Object))

                str.AppendLine("[")

                First = True
                For Each obj In kv.Value
                    If First Then
                        First = False
                    Else
                        str.AppendLine(",")
                    End If
                    str.Append(Tabs(TabLvl + 1) & GetObjString(TabLvl + 1, obj))
                Next

                str.AppendLine()
                str.Append(Tabs(TabLvl) & "]")

            Case Else

                str.Append(GetObjString(TabLvl + 1, kv.Value))

        End Select

        Return str.ToString

    End Function

    Private Function GetObjString(ByVal TabLvl As Integer, ByRef obj As Object) As String
        Dim kv0 As KeyValuePair(Of String, Object)
        Dim First As Boolean
        Dim str As System.Text.StringBuilder

        If obj Is Nothing Then
            Return "null"
        Else
            Select Case obj.GetType

                Case GetType(Dictionary(Of String, Object))

                    str = New System.Text.StringBuilder
                    str.AppendLine("{")

                    First = True
                    For Each kv0 In obj
                        If First Then
                            First = False
                        Else
                            str.AppendLine(",")
                        End If
                        str.Append(GetKeyValString(TabLvl + 1, kv0))
                    Next

                    str.AppendLine()
                    str.Append(Tabs(TabLvl) & "}")

                    Return str.ToString

                Case GetType(String)

                    Return ChrW(34) & CStr(obj) & ChrW(34)

                Case GetType(Boolean)

                    If CBool(obj) Then
                        Return "true"
                    Else
                        Return "false"
                    End If

                Case Else

                    Return CDbl(obj).ToString

            End Select
        End If


    End Function

    Private Function Tabs(ByVal l As Integer) As String
        Dim i As Integer
        Dim str As String

        str = ""
        For i = 1 To l
            str &= vbTab
        Next

        Return str
    End Function

    Private Function GetObject() As Dictionary(Of String, Object)
        Dim MyDic As Dictionary(Of String, Object)
        Dim key As String
        Dim obj As Object
        Dim i As Integer
        Dim i2 As Integer
        Dim Valstr As String
        Dim ValList As List(Of Object) = Nothing
        Dim ArrayMode As Boolean = False

        'remove {
        fullfile = (Right(fullfile, Len(fullfile) - 1)).Trim

        'new list of key/value pairs
        MyDic = New Dictionary(Of String, Object)


        'loop through key/value pairs
lb10:
        If Left(fullfile, 1) <> ChrW(34) Then
            Throw New Exception
            Return Nothing
        End If

        'get key
        i = fullfile.IndexOf(ChrW(34), 1)
        key = Mid(fullfile, 2, i - 1)
        fullfile = (Right(fullfile, Len(fullfile) - i - 1)).Trim
        fullfile = (Right(fullfile, Len(fullfile) - 1)).Trim

        If key = "" Then
            Throw New Exception
            Return Nothing
        End If

        'get value (object, number, boolean, array)
        If Left(fullfile, 1) = "[" Then
            ArrayMode = True
            fullfile = (Right(fullfile, Len(fullfile) - 1)).Trim
            ValList = New List(Of Object)
        End If

lb20:
        If Left(fullfile, 1) = "{" Then
            obj = GetObject()
        Else
            If Left(fullfile, 1) = ChrW(34) Then
                'string
                i = fullfile.IndexOf(ChrW(34), 1)
                obj = Mid(fullfile, 2, i - 1)
                fullfile = (Right(fullfile, Len(fullfile) - i - 1)).Trim
            Else
                'number/boolean
                i = fullfile.IndexOf(",", 1)
                i2 = fullfile.IndexOf("}", 1)

                If i = -1 Then
                    If i2 = -1 Then
                        Valstr = Right(fullfile, Len(fullfile) - 1)
                        fullfile = ""
                    Else
                        Valstr = Mid(fullfile, 1, i2)
                        fullfile = (Right(fullfile, Len(fullfile) - i2)).Trim
                    End If
                Else
                    If i2 = -1 Or i < i2 Then
                        Valstr = Mid(fullfile, 1, i)
                        fullfile = (Right(fullfile, Len(fullfile) - i)).Trim
                    Else
                        Valstr = Mid(fullfile, 1, i2)
                        fullfile = (Right(fullfile, Len(fullfile) - i2)).Trim
                    End If
                End If

                If IsNumeric(Valstr) Then
                    obj = CDbl(Valstr)
                ElseIf (UCase(Valstr)).Trim = "FALSE" Then
                    obj = False
                ElseIf (UCase(Valstr)).Trim = "TRUE" Then
                    obj = True
                ElseIf (UCase(Valstr)).Trim = "NULL" Then
                    obj = Nothing
                Else
                    Throw New Exception
                    Return Nothing
                End If

            End If
        End If

        If ArrayMode Then
            ValList.Add(obj)
            If Left(fullfile, 1) = "]" Then
                ArrayMode = False
                fullfile = (Right(fullfile, Len(fullfile) - 1)).Trim
                MyDic.Add(key, ValList)
            End If
        Else
            MyDic.Add(key, obj)
        End If

        If Left(fullfile, 1) = "," Then
            fullfile = (Right(fullfile, Len(fullfile) - 1)).Trim
            If ArrayMode Then
                GoTo lb20
            Else
                GoTo lb10
            End If
        End If

        If Left(fullfile, 1) = "}" Then
            fullfile = (Right(fullfile, Len(fullfile) - 1)).Trim
        End If

        Return MyDic


    End Function


#End Region



End Class