JSONSelector

Specify which record member needs to be serialized or deserialized.

Syntax

JSONSelector is a mandatory attribute used with JSONOneOf.

Usage

In an operation that you set JSONOneOf to specify members of a record or a user-defined type that need to be serialized or deserialized, you must set the JSONSelector on a specific member of the record to perform the selection. This specific member must be of type SMALLINT or INTEGER.

The JSONSelector attribute supports the oneOf keyword in the JSON schema property of the Swagger and OpenAPI specifiaction.

Example using JSONSelector and JSONOneOf

In this example, the JSONSelector attribute is set on the _selector member in the input record of the CreateAccount function. At a request to the service, you can choose which member of the createAccountType record – id or name – to use by setting the _selector to the index value of the record member. For example, to specify the name, in the client set _selector to 2 in the statement LET in._SELECTOR=2.

In the CreateAccount function, the CASE statement tests for the _selector value.

IMPORT COM

PUBLIC TYPE accountType RECORD
    id INTEGER,
    name STRING,
    date DATETIME YEAR TO SECOND,
    age INTEGER,
    gender BOOLEAN
END RECORD

PRIVATE DEFINE accounts DYNAMIC ARRAY OF accountType

PUBLIC DEFINE accountError RECORD ATTRIBUTE(WSError = 'account service error')
    id INTEGER,
    msg STRING
END RECORD

TYPE createAccountType RECORD ATTRIBUTE(JSONOneOf)
    _selector INTEGER ATTRIBUTE(JSONSelector),
    id INTEGER,
    name STRING
END RECORD

FUNCTION CreateAccount(
    in createAccountType)
    ATTRIBUTE(WSPost, WSPath = "/createaccount")
    RETURNS(createAccountType)
    DEFINE out createAccountType
    DEFINE idx INTEGER
    LET out = in

    CASE
        WHEN in._selector = 1
            LET idx = accounts.search("id", in.id)
            IF idx > 0 THEN
                # raise RESTError with accountError
            ELSE
              CALL accounts.appendElement()
              LET accounts[accounts.getLength()].id = in.id
            END IF
        WHEN in._selector = 2
            LET idx = accounts.search("name", in.name)
            # ... function code ... 
    END CASE

    RETURN out
END FUNCTION