today I had to serialize and to unserialize JSON data.
The code Microsoft showed in his samples is here: https://docs.microsoft.com/en-us/dotnet ... -json-data
Using a static class with static methods simplified things very much:
Code: Select all
using System.Runtime.Serialization
using System.Runtime.Serialization.Json
using System.IO
static class JsonHelper
static method Serialize<T>( oObject as T ) as string
local oSerializer as DataContractJsonSerializer
local oStream as MemoryStream
local oReader as StreamReader
local cResult as string
oSerializer := DataContractJsonSerializer{ typeof( T ) }
oStream := MemoryStream{}
oSerializer:WriteObject( oStream, oObject )
oStream:Position := 0
oReader := StreamReader{ oStream }
cResult := oReader:ReadToEnd()
oReader:Close()
oReader:Dispose()
oStream:Close()
oStream:Dispose()
return cResult
static method Deserialize<T>( cJsonString as string ) as T
local oResult as T
local oStream as MemoryStream
local oWriter as StreamWriter
local oSerializer as DataContractJsonSerializer
oStream := MemoryStream{}
oWriter := StreamWriter{ oStream }
oWriter:Write( cJsonString )
oWriter:Flush()
oStream:Position := 0
oSerializer := DataContractJsonSerializer{ typeof( T ) }
oResult := ( T ) oSerializer:ReadObject( oStream )
oWriter:Close()
oWriter:Dispose()
oStream:Close()
oStream:Dispose()
return oResult
end class
Code: Select all
oLoginData := LoginData{ "user", "pass" }
cJsonString := JsonHelper.Serialize<LoginData>( oLoginData )
System.Console.WriteLine( cJsonString )
oLoginData := JsonHelper.Deserialize<LoginData>( cJsonString )
System.Console.WriteLine( String.Format( "Login:{0}, Password:{1}", oLoginData:username, oLoginData:password ) )
Wolfgang
P.S. to make this work, you need the System.Runtime.Serialization and System.XML assemblies in the references.
And here is a small XIDE export file with sample code: