Question
· Dec 7, 2023

Convert JSON array to the list of objects

I want to call the REST endpoint and return the list of objects. I`ve created the method but it displays an error: 

<METHOD DOES NOT EXIST>GetAllPersons+10^Lab3.RestClient.1 *Count,%ZEN.proxyObject

ClassMethod GetAllPersons() As %Status
{
    Set request = ##class(%Net.HttpRequest).%New()
    Set sc = request.Get("http://localhost:52773/csp/crud/persons") 
    Quit:$System.Status.IsError(sc) sc

    Set responseStream = ##class(%Stream.GlobalBinary).%New()
    Set response = request.HttpResponse.Data.Read()
    
    Write "Response from Server:", !, response, !

    Set pl = ##class(%ListOfObjects).%New()

    set sc = ##class(%ZEN.Auxiliary.jsonProvider).%ConvertJSONToObject(response, , .pl)
    Quit:$System.Status.IsError(sc) sc

    for i = 1:1:pl.Count() {
        Set p = pl.GetAt(i)
        Write "Name: ", p.Name, !
        Write "Gender: ", p.Gender, !
    }
    
    Quit $$$OK
}

Here is an example of a rest call via ARC:

Not sure if  %ConvertJSONToObject is used properly but I did not find another

Product version: IRIS 2023.2
Discussion (2)2
Log in or sign up to continue

In your example call, the top level is a JSON object, not an array so iterating over it won't work.  You would need to access it from the children property

However, he ZEN JSON functionality is deprecated in recent versions of IRIS, and the native JSON support is a bit friendlier to use.  The documentation is here: https://docs.intersystems.com/irislatest/csp/docbook/DocBook.UI.Page.cls...

If you use

set obj =  {}.%FromJSON(%request.HttpResponse.Data) 

you should get access to the json object, and then you can use %GetIterator to cycle over the array