### Parse Save JSON Object

An example of parsing & saving an OBJECT from/to a JSON File.
B4J Library required: Json.
In Summary:
• Define and init a global map holding the information from the JSON File.
• Parse the JSON File to the Map.
• Use the data from the Map using GetDefault. Save the Map to the JSON File.
JSON File Structure
Note: do not use the brackets [], only one pair of {}.
{
"windowtop": "128",
"windowwidth": "845",
"windowleft": "377",
"windowheight": "494"
}
Define Globals and Init the Map
' Map holding the content of the JSON File
Private gSettings As Map
' JSON File
Private gSettingsFile As String = "settings.json"
Init:
gSettings.Initialize
Parse the JSON File into Global Map
Define a Sub parsing the settings from the JSON file into global settings map gSettings.
`Sub readSettings
Dim parser As JSONParser
Try
' Init the parser with the content of the file to parse
parser.Initialize(File.ReadString(File.DirApp, gSettingsFile))
gSettings = parser.NextObject
' Read the object into the global settings map
MainForm.WindowTop = gSettings.GetDefault("windowtop", 200)
MainForm.WindowLeft = gSettings.GetDefault("windowleft", 200)
MainForm.WindowWidth = gSettings.GetDefault("windowwidth", 1000)
MainForm.WindowHeight = gSettings.GetDefault("windowheight", 500)
Catch
Log("Read Settings Error" & CRLF & LastException.Message)
End Try
End Sub`
Save the Global Map to the JSON File
Define a Sub to save the settings to the JSON file from the global settingsmap.
`Sub saveSettings
Dim JSONGenerator As JSONGenerator
Try
JSONGenerator.Initialize(gSettings)
File.WriteString(File.DirApp, gSettingsFile, JSONGenerator.ToPrettyString(2))
Catch
Log("Save Settings Error" & CRLF & LastException.Message)
End Try
End Sub`

Changed: , Category: JSON, File: T6C210M1538.htm, ID: 1538