-2

I am trying to wrap a request body from callin request which has a variable but values can be different data types.

Example request body 1 :

{
RecordId:"cncjdn"
}

Example request body 2 :

{
RecordId:"['cncjdn','dccwxass']"
}

In the above example request bodies, I have same key but values are of different datatype. I should be able to accept single RecordId or List of RecordId in the same variable. I cannot have separate variables for String and List in request body

In RestResource, I have wrapper class to which the request body will get de-serialized and assigned

public class RequestWrapper{
   public String RecordId;
}

RequestWrapper w = (RequestWrapper)JSON.deserialize(req.requestBody.toString(),RequestWrapper.class);

The JSON.deserialize works only when Request body has String type data. How can I determine the datatype and map it to a variable having relevant datatype ?

1
  • 2
    You can only deal with this by using untyped deserialization or your own JSON parser.
    – Phil W
    Commented Sep 20, 2023 at 18:52

1 Answer 1

2

You would have to have two different wrappers, and choose the appropriate one. Apex is a strongly typed language, so the same symbol can't be used as two different types. Alternatively, as Phil says, use deserializedUntyped instead:

Id singleRecordId;
Id[] multipleRecordId;
Map<String, Object> result = (Map<String, Object>)JSON.deserializeUntyped(req.requestBody.toString());
Object recordId = result.get('recordId');
if(recordId instanceOf Id) {
  singleRecordId = (Id)recordId;
} else if(recordId instanceOf List<Object>) {
  multipleRecordId = new Id[0];
  for(Object recId: (List<Object>)recordId) {
    multipleRecordId.add((Id)recId);
  }
} else {
  // Handle property not found
}

Note that deserializeUntyped can't automatically determine types, so we have to do a manual check, and some casting is involved.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .