• Skip to main content
  • Skip to footer

B4X

Develop Android, iOS and IoT applications

  • Home
  • Products
    • B4A (Android)
    • B4i (iOS)
    • B4J (Desktop)
    • B4R (Arduino)
  • Showcase
  • Store
  • Learn
    • General
    • Guides
    • Video Tutorials
    • Glossary
  • Teach
  • Blog
  • Community
A B C D F G H J M N Q S T U X

All

JSON

JSON – JavaScript Object Notation, is a popular text format and for a good reason. It is human readable, simple, compact, relatively fast to parse and nicely mapped to Lists and Maps.
Example of a JSON string:

{
    "Version": 1,
    "Items": [
        {
            "Count": 10,
            "Name": "Item #1"
        },
        {
            "Count": 2,
            "Name": "Item #2"
        },
        {
            "Count": 43,
            "Name": "Item #3"
        }
    ],
    "ID": "abcdef"
}

Elements inside curly brackets { … } are mapped to Map collections and elements inside square brackets [ … ] are mapped to List collections.
The above string is created with this code:

Dim Data As Map = CreateMap("Version": 1.00, "ID": "abcdef", _
	"Items": Array( _
		CreateMap("Name": "Item #1", "Count": 10), _
		CreateMap("Name": "Item #2", "Count": 2), _
		CreateMap("Name": "Item #3", "Count": 43)))
Dim jg As JSONGenerator
jg.Initialize(Data)
Dim JsonString As String = jg.ToPrettyString(4)
Log(JsonString)

Parsing this string is simple:

Dim parser As JSONParser
parser.Initialize(JsonString)
Data = parser.NextObject
Dim Items As List = Data.Get("Items")
For Each m As Map In Items
	Log(m.Get("Name") & ": " & m.Get("Count"))
Next

In B4X you can parse and generate JSON strings with the Json library. In B4R, where the memory is very limited, it requires a bit more work: https://www.b4x.com/android/forum/threads/107410
There is an online B4J tool that can help with parsing JSON strings: https://b4x.com:51041/json/index.html

Don’t rely on the order of elements in the map collections. If the order needs to be preserved then use a list, it can be a list of maps.

Don’t try to generate JSON strings without JsonGenerator. Some of the characters need to be escaped and you will just waste your precious time.

Written by Erel Uziel

Footer

Top

  • Home
  • Products
    • B4A (Android)
    • B4i (iOS)
    • B4J (Desktop)
    • B4R (Arduino)
  • Showcase
  • Store
  • Learn
    • General
    • Guides
    • Video Tutorials
    • Glossary
  • Teach
  • Blog
  • Community

About us

Follow us:

Latest Versions

B4A v10.5 (changelog)
B4i v6.80 (changelog)
B4J v8.80 (changelog)
B4R v3.50 (changelog)

Contact Us

support@basic4ppc.com

Privacy Policy

Privacy Policy

Copyright © 2021 · Anywhere Software. Android is a trademark of Google Inc. iOS is a registered trademark of Apple. Arduino is a trademark of Arduino. Java is a trademark of Oracle.