### Parse Save JSON Array

An example of parsing & saving an ARRAY 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.
Define JSON Array File Structure
Filename: smtpconfig.json
[
{
"password": "PASSWORD",
"port": "25",
"receipient": "receipient@name.de",
"mailserver": "smtp.strato.de",
"username": "user@name.de"
}
]
Define global map holding the JSON Array Structure
`Sub Class_Globals
...
Private gmapSettings As Map
...
End Sub`
Init the global Map:
gmapSettings.Initialize
Parse the JSON file into the global Map
Dim JSON As JSONParser
JSON.Initialize(File.ReadString(File.DirApp, "smtpconfig.json"))
Dim l As List
l = JSON.NextArray
gmapSettings = l.Get(0)
Note
As the JSON file uses [ ], a list is required to parse the array within the [ {},{} ].
Use the global map entries
gmapSettings.Get("mailserver")
gmapSettings.Get("port")
gmapSettings.Get("username")
gmapSettings.Get("password")
Update the map entries
gmapSettings.Put("mailserver", "newvalue")
gmapSettings.Put("port", "newvalue")
...
Save the global map to the JSON file
Dim JSONGenerator As JSONGenerator
Dim Data As List
Data.Initialize
Data.Add(gmapSettings)
JSONGenerator.Initialize2(Data)
File.WriteString(File.DirApp, "smtpconfig.json", JSONGenerator.ToPrettyString(2))
Another example reading JSON File with multiple arrays
Note that special characters are used in the field content.
Structure JSON File "import.json"
[
{"title" :"title1", "category": "category1", "content": "content"},
{"title" :"title2", "category": "category2", "content": "content"}
]
Parse JSON File "import.json"
Dim parser As JSONParser
parser.Initialize(File.ReadString(File.DirApp, "import.json"))
Dim root As List = parser.NextArray
For Each colroot As Map In root
Dim content As String = colroot.Get("content")
Dim category As String = colroot.Get("category")
Dim title As String = colroot.Get("title")
'
' Do something with the title, category and content
'
Next
Save JSON File "export.json"
' OPTION 1 using a list of maps. each map holds a record
' Here a tableview tvwMain is used
Dim JSONGenerator As JSONGenerator
Dim Data As List
Data.Initialize
For i = 0 To tvwMain.Items.Size - 1
Dim row() As Object = tvwMain.Items.Get(i)
Dim m As Map = CreateMap("id": row(0), "title": row(1), "category": row(2), "content": row(3))
Data.Add(m)
Next
JSONGenerator.Initialize2(Data)
File.WriteString(File.DirApp, "export.json", JSONGenerator.ToPrettyString(2))
Result looks like:
[
{"ID":"16","Title":"title1","Category":"category1","Content":"Line1\r\n' Comment\r\n

\r\nline2\r\nLine3"},
{"ID":"17","Title":"title2","Category":"category2","Content":"Line1\r\nLine2\r\nLine3"}
]

Changed: , Category: JSON, File: T6C210M1537.htm, ID: 1537