B4J Question What's up with JSON?

boten

Active Member
Licensed User
Longtime User
this is the code, a very simple map, each value is a type

B4X:
Sub Process_Globals
   Dim mp As Map
   Type tp(a As String,z As String)
End Sub

Sub AppStart (Form1 As Form, Args() As String)
   mp.Initialize
   
   Dim t As tp
   t.Initialize
   t.a="aaa"
   t.z="AAA"
   mp.Put(1,t)
   
   Dim t As tp
   t.Initialize
   t.a="bbb"
   t.z="BBB"
   mp.Put(2,t)
   
   Dim t As tp
   t.Initialize
   t.a="ccc"
   t.z="CCC"
   mp.Put(3,t)
   
   Dim js As JSONGenerator
   Dim s As String
   js.Initialize(mp)
   s=js.ToPrettyString(3)
  Log(s)   
   Dim msg As Msgboxes
   msg.Show("done","")
End Sub

the log output is:
B4X:
Program started.
{
  "1": "[IsInitialized=true, a=aaa, z=AAA\n]",
  "2": "[IsInitialized=true, a=bbb, z=BBB\n]",
  "3": "[IsInitialized=true, a=ccc, z=CCC\n]"
}

Why the Isinitialize appears, and how to get rid of it?
Why the "\n" and how to get rid of it?
 

rwblinn

Well-Known Member
Licensed User
Longtime User
Hi,

do not think JSON can handle types as it requires strings.

What output do you want?

You can test JSON formats by using the JSON Online Parser - it will provide example code and outputs.
 
Upvote 0

sorex

Expert
Licensed User
Longtime User
that's normal behaviour I guess as the isInitialized is a property value just like the other tho.

you can always write your own json string builder to get rid of it if that jsongenerator doesn't have a way to add items one by one.
 
Upvote 0

Roycefer

Well-Known Member
Licensed User
Longtime User
It is often convenient to write one's own ToJSONString() method for custom classes and types. This is especially easy for a simple type like yours:
B4X:
Sub tpToJSONString(teepee as tp) As String
    Return "{a:" & teepee.a & ",z:" & teepee.z & "}"
End Sub

Then, while building your larger JSON String, call
B4X:
mp.Put(1,tpToJSONString(t))
'instead of
'mp.Put(1,t)
 
Upvote 0

Erel

B4X founder
Staff member
Licensed User
Longtime User
If you want to serialize custom types with json then you should create a sub that converts the type to a Map:
B4X:
Sub TpToMap(teepee As TP) As Map
 Return CreateMap("a": teepe.a, "b": teepe.b)
End Sub

Now you can convert the types to json with:
B4X:
Dim t1, t2, t3 As TP
... fill the types
Dim jg As JsonGenerator
jg.Initialize(CreateMap(1: TpToMap(t1), 2: TpToMap(t2), 3: TpToMap(t3)))
 
Upvote 0

boten

Active Member
Licensed User
Longtime User
So essentially for the json at question - create map of maps

If you want to serialize custom types with json then you should create a sub that converts the type to a Map:
B4X:
Sub TpToMap(teepee As TP) As Map
Return CreateMap("a": teepe.a, "b": teepe.b)
End Sub

Now you can convert the types to json with:
B4X:
Dim t1, t2, t3 As TP
... fill the types
Dim jg As JsonGenerator
jg.Initialize(CreateMap(1: TpToMap(t1), 2: TpToMap(t2), 3: TpToMap(t3)))
 
Upvote 0
Top