I have a situation where when I make a callout I get a single json response like this:
{
"Person": {
"Infomration": {
"IndividualInformation": {
"IndividualCode": "XXXXXX",
"IndividualType": {
"Resident": 0,
"Alive": "Yes",
}
},FamilyInformation": {
"FamilyCode": 0101010,
"PresentInFamily": 1
}
},
..... a really long json reponse
}
Notice that there is only a single {}
indicating a single element. The problem is that sometimes the external system can send more than one person
depending of the search result of the external system. I was not given a sample array response, but I am assuming it will be with like this:
[{
"Person": {
"Infomration": {
"IndividualInformation": {
"IndividualCode": "XXXXXX",
"IndividualType": {
"Resident": 0,
"Alive": "Yes",
}
},FamilyInformation": {
"FamilyCode": 0101010,
"PresentInFamily": 1
}
},
.....
}, "Person": {
"Infomration": {
"IndividualInformation": {
"IndividualCode": "XXXXXX",
"IndividualType": {
"Resident": 0,
"Alive": "Yes",
}
},FamilyInformation": {
"FamilyCode": 0101010,
"PresentInFamily": 1
}
},
.....
}]
I am trying to handle this as there are 2 different reponses. I tried using JSON.deserializeUntyped
. But for single reponse I have to use this (Map<String, Object>)JSON.deserializeUntyped(jsonBody);
. Obviously doesn't work for array of response. For array I have to use (List<Object>) JSON.deserializeUntyped(jsonBody);
. I can't simply cast it (List<Object>)
for both array and single.
The only solution I found was:
String respBody = res.getBody();
if(!respBody.left(1).equalsIgnoreCase('[')) respBody = '[' + res.getBody() + ']';
dataFromSystemExternal = (List<ResponseSystemExternal>) JSON.deserialize(respBody, List<ResponseSystemExternal>.Class);
Basically, I am checking the very first char of the respBody
to see if it is a '['. If not I am enclosing the respBody
between '[' and ']' and deserializing the respBody
into a List.
Is there any other solution?