B4J Question JSON Generator

Philip Prins

Active Member
Licensed User
Longtime User
Hello , i found the JSON parser tool , but it would be nice to have a JSON generator tool as well,

I am struggling to generate the following in B4X:

{"data" : [

{
"context" : "00036",
"dns" : "1.1.1.7"
}
],
"id" : "8881002",
"ip" : "195.231.3.86",

"password" : "adminl23",
"port" : "8062"
}

Any help is highly appreciated
 
Solution
B4X:
'To achieve the following:
    Dim targetJSON As String = $"
{"data" : [

{
"context" : "00036",
"dns" : "1.1.1.7"
}
],
"id" : "8881002",
"ip" : "195.231.3.86",

"password" : "adminl23",
"port" : "8062"
}
"$

'Do this:
    Dim list1 As List
    list1.Initialize
    list1.Add(CreateMap("context": "00036", "dns": "1.1.1.7"))
    Dim mp As Map = CreateMap("data": list1, "id": "8881992", "ip": "195.231.3.86", "password": "admin123", "port": "8062")
    Log(mp.As(JSON).ToString)
   
'Result
    Dim theLogShows As String = $"
{
    "password": "admin123",
    "data": [
        {
            "context": "00036",
            "dns": "1.1.1.7"
        }
    ],
    "port": "8062",
    "ip": "195.231.3.86",
    "id": "8881992"
}
"$  

'Since...

William Lancee

Well-Known Member
Licensed User
Longtime User
B4X:
'To achieve the following:
    Dim targetJSON As String = $"
{"data" : [

{
"context" : "00036",
"dns" : "1.1.1.7"
}
],
"id" : "8881002",
"ip" : "195.231.3.86",

"password" : "adminl23",
"port" : "8062"
}
"$

'Do this:
    Dim list1 As List
    list1.Initialize
    list1.Add(CreateMap("context": "00036", "dns": "1.1.1.7"))
    Dim mp As Map = CreateMap("data": list1, "id": "8881992", "ip": "195.231.3.86", "password": "admin123", "port": "8062")
    Log(mp.As(JSON).ToString)
   
'Result
    Dim theLogShows As String = $"
{
    "password": "admin123",
    "data": [
        {
            "context": "00036",
            "dns": "1.1.1.7"
        }
    ],
    "port": "8062",
    "ip": "195.231.3.86",
    "id": "8881992"
}
"$  

'Since order is not relevant and white space is ignored this is equivalent to the target
 
Upvote 1
Solution

DonManfred

Expert
Licensed User
Longtime User
I am struggling to generate the following in B4X
a few tips

- if a element in the json starts wir a { then we need to use a Map in B4X
- if a element in the json starts wir a [ then we need to use a List in B4X

So to generate the json with B4X you just have to Build a Map/List- or List/Map- Structure and then use the JSONGenerator to build the json.

This code generates the json from #1. Note that the keyorder in a Map does not matter.
B4X:
    Dim m As Map
    m.Initialize
   
    Dim l As List
    l.Initialize
   
    Dim data As Map = CreateMap("context" : "00036",    "dns" : "1.1.1.7")
    l.Add(data)
   
    m.Put("data",l)
    m.Put("password","adminl23")
    m.Put("port", "8062")
   
    Dim jgen As JSONGenerator
    jgen.Initialize(m)
    Log("json")
    Log(jgen.ToString)
    Log("Pretty")
    Log(jgen.ToPrettyString(2))
 
Last edited:
Upvote 0
Top