[SalesForce] Deserialize an object with an optional field

I am trying to deserialize a request body but need to allow one of the fields to be optional.

RequestBody {
   Decimal someNumber;
}

RequestBody reqBody = (RequestBody)JSON.deserialize(req.requestBody.toString(), RequestBody.class);

MyCustomObject obj = new MyCustomObject();

obj.someNumber = reqBody.someNumber;

If the field age is empty, it gets sent in as an empty string, and I just get a 500 Server Error as my response. How can I allow this to just be null if it's empty?

Best Answer

  • In case all values form JSON are comming as strings { "key" : "value" }, you can

Map < String, Object > bodyMap = JSON.deserializeUntyped(req.requestBody.toString());

if (bodyMap.containsKey('age') && String.isNotEmpty((String)bodyMap.get('age')) { obj.someNumber = (Integer) bodyMap.get('age');

}

do the same for all variables you want to set (look carefuly to cast each value to the proper primitive data types)

  • otherwise you will have to check the values instances

    • bodyMap.get('age') instanceOf String
    • bodyMap.get('age') instanceOf Integer

and properly handle each data type

Good luck!

Related Topic