(PB 2017 R3 build 1858 / Windows 10 )
From an httpclient object I receive JSON strings that I need to parse. They may be quite complicated with deeply nested structures.
My first problem is to parse NULL values.
My preliminary code looks like this:
ls_result = ij_parser.loadstring(as_json)
ll_root = ij_parser.getrootitem( )
//
...
this.ErrorDetails = ij_parser.getitemstring(ll_root,"ErrorDetails")
this.ErrorMessage= ij_parser.getitemstring(ll_root,"ErrorMessage")
this.Successful= ij_parser.getitemboolean(ll_root,"Successful")
...
and so on for the various elements. I know the expected datatypes, of course.
However, there may be a null or more in the dataset, like this:
"Successful":true,"ErrorMessage":null,"ErrorDetails":null
This code causes runtime exceptions, rather than returning null strings. Why? Buggy parser? I would have expected null strings to be returned.
To avoid it I have to wrap every getitem in aTRY-CATCH block , and do a setnull in the catch part. Yikes.
Is there a better way without going completely low-level?
I can successfully get an array of objects by using the JSONPackage.GetValue, and a small homemade function to seperate the items in the square bracket enclosed result. That is enough to pass the individual item strings on to the parser method of the subordinated object(s). In this way any object in the hierarchy only has to deal with keys on its own level. The price to pay is to write a parser method in every data contract nvo.
Then finally there is the last (?) problem, boolean values. They are not strings, so there is no JSONPackage primitive to access them. Seems I have to put a JSONParser object in my wrapper object as well to do this.
JSONPackage.GetValue("Successful") causes runtimeerror whatever value, false or true.
I have abandoened the idea of making wrapper object around a JSONPackage instance, it is currently not designed for general parsing of JSON strings. Seems I must use same approach, but based on the JSONParser. Maybe I need both.
regards sverre
Unfortunately for the boolean, you're going to have to use JSONParser. The JSONPackage doesn't support boolean and apparently null either. These are both bugs, although the boolean would probably be an enhancement request. You will have to use the JSONParser for this one unfortunately. Here's some code to get the value for the Successful key:
boolean lb_success
string ls_json
long ll_root
jsonparser ljp_parse
try
ljp_parse = create jsonparser
ls_json = "the json you posted"
ljp_parse.Loadstring( ls_json )
ll_root = ljp_parse.GetRootItem()
lb_success = ljp_parse.getitemboolean(ll_root, "Successful")
MessageBox("", String(lb_success))
catch(runtimeerror re)
MessageBox("RuntimeError", re.getmessage())
finally
IF IsValid(ljp_parse) THEN
destroy ljp_parse
END IF
end try