Read a decimal from a JSON response without crashing on null
AL (Business Central)A guard that returns false instead of throwing when a field is missing or the service starts sending null.
local procedure TryGetDecimal(Payload: JsonObject; FieldName: Text; var Value: Decimal): Boolean
var
Token: JsonToken;
begin
Value := 0;
if not Payload.Get(FieldName, Token) then
exit(false);
if not Token.IsValue() then
exit(false);
if Token.AsValue().IsNull() then
exit(false);
Value := Token.AsValue().AsDecimal();
exit(true);
end;Note
AsDecimal() throws on a null token, so IsNull() has to be checked separately from Get(). Both guards are needed.
- AL
- Business Central
- REST APIs
