0

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?

  • I Do not see age and not sure about your 500 error you can try this for assignment obj.someNumber = reqBody <> NULL && reqBody.someNumber<> NULL? reqBody.someNumber : NULL; are you saying someNumber is not present whre from you are getting theJSON – Avijit Chakraborty Jan 24 at 3:42
1
  • 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!

| improve this answer | |
0

A number field that is blank should not be sent as an empty string. It should either be omitted entirely or set to the value null (without quotes).

When there's a value:

{ "someNumber": 5 }

When the value is null:

{ "someNumber": null }

Or you can just omit it entirely:

{ }

If you can't control the JSON, then you'll have to use JSON.deserializeUntyped to determine if it is a string or not:

Map<String, Object> reqBody = (Map<String, Object>)JSON.deserializeUntyped(req.requestBody.toString());
Object someValue = reqBody.get("someValue");
if(someValue instanceOf Integer) {
    // Do something with it as a number
    Integer someValueInt = (Integer)someValue;
} else {
    // It's a string, or null, or whatever
}
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.