JSONImporting an array without a key
I'm receiving a JSON payload via a REST API, I'd like to %JSONImport this stream into a class which extends %JSON.Adaptor. The problem is that the JSON is an array whose elements have no key (as you can see in the example JSON below). Right now I'm having to do some manipulations to convert the stream into a dynamic object and do a %Set which inserts a made up key "record" so "thingone" and "thingtwo" have an associated key that I can use when referencing "thingone" and "thingtwo"...such as record.GetAt(1).thingone
I'm also finding myself having to do the reverse when sending payloads back out and removing "record". Is there a way I can build my class so I don't have to do those manipulations? Or is there just a better way?
Below is how the JSON comes in from the remote system.
[
{
"thingone": "Red",
"thingtwo": "Green"
},
{
"thingone": "Blue",
"thingtwo": "Yellow"
}
]Comments
You can access your elements by this way (for the example, your object is named jsObj)
w jsObj.%Get(0).thingone,!
Red
w jsObj.%Get(0).thingtwo,!
Green
w jsObj.%Get(1).thingone,!
Blue
w jsObj.%Get(1).thingtwo,!
Yellow
Caution : For dynamic array, first element is indexed by 0, not 1 like ObjectScript standard arrays
I wasn't exactly clear with my problem. I need to %JSONimport into my class (the class which extends %JSON.Adaptor and either Ens.Request or Ens.Response)
Thank you
Class DC.Import Extends (%Persistent, %JSON.Adaptor)
{
Property thingone As %String;
Property thingtwo As %String;
ClassMethod Test()
{
// create a test stream
set myStream=##class(%Stream.TmpCharacter).%New()
do myStream.Write("[{""thingone"":""Red"",""thingtwo"":""Green""},{""thingone"":""Blue"",""thingtwo"":""Yellow""}]")
// convert input (JSON) stream into a JSON object
set data={}.%FromJSON(myStream)
// loop over the JSON-Array and import each array element into your database
for i=0:1:data.%Size()-1 {
set obj=..%New()
set sts=obj.%JSONImport(data.%Get(i))
if sts set sts=obj.%Save()
if sts continue
write "Error: i=",i,", reason=",$system.Status.GetOneErrorText(sts),!
}
}Of course, instead of "myStream" you should use your REST-input stream.
do ##class(DC.Import).Test()
zwrite ^DC.ImportD
^DC.ImportD=2
^DC.ImportD(1)=$lb("","Red","Green")
^DC.ImportD(2)=$lb("","Blue","Yellow")