Android Question Automatic mapping of type fields and variables

bluedude

Well-Known Member
Licensed User
Longtime User
Hi,

I'm getting JSON from a server and this contains stuff like "address","firstname" etc. I want to map these automatically to my defined type without using case or if statements.

Type Record (address as string,firstname as string)

Normally you would do

Dm newRecord as Record
newRecord.address = "test"

But I want to get the address field name in a variable and do something like newRecord.$field = json value

$field = json fieldname
newRecord.$field

Is that actually possible in B4A?
 
Not exactly what I mean, parsing and assigning variables is not the problem. I want to get the fields from json too and say newRecord.fieldvariable

So instead of saying :

newRecord.address = "test" I want to do

newRecord.fieldvariable="test" where fieldvariable is address which I got from the json file.

So basically i'm getting the type property from the json. If this is possible it would be easier because I don't need to do select case statements etc.
 
Upvote 0
See jsontree to get the right code to "read and parse" the jsonstring in b4a
 
Upvote 0
Sorry guys, this is not about json parsing!

It is about mapping a variable name that is in json to for example a property of a view or a property of a defined type. See my sample in this question. So basically the property name is what I get from JSON.

I don't want to do:

if json fieldname = "address" then
newRecord.address = json fieldname value

I want to do newRecord.jsonfieldname= "test"

I have no other way to explain this better unfortunately.
 
Upvote 0
Sort of. You can use CallSub3 to do this:

Code: Copy
CallSub3("","Set" & json.fieldname,newRecord,  json.fieldname.value)

Sub Setaddress(setRecord as record, address as string)
  setRecord.address = address
End sub
 
Upvote 0
Again, not the point :-) The whole thing is to do the .address assignment by using a variable instead of saying it is the address property.

I want to loop through the json which has all the field names defined in my type. Then I want to do fieldname = json fieldname and then newRecord.fieldname

In this case fieldname is a variable defined as string.
 
Upvote 0
Yes I know. But AFAIK B4A doesn't do macro substitution or have an Eval function like JavaScript. Only interpreted languages support those features usually.
 
Upvote 0
Back
Top