3

I am receiving the following error in my Apex runtime:

JSONException: Expected List<ApexBatch.SFError> but found {

It's do with how I'm assigning the response to my wrapper but I'm not sure how I need to parse:

Wrapper Classes

public class CustomResponse {
   public boolean isSuccess;
   public List<CustomError> errors;
}

public class CustomError {
    public String Id;
    public String error;
}

Example JSON Response:

{"IsSuccess":false,"Errors":{}}

... and heres one with errors:

{"isSuccess":true,"Errors":{"123":"error code here", "123":"error code here"}}

Apex which assigns to wrapper:

    CustomResponse calloutBody = (CustomResponse)JSON.deserialize(
response.getBody(), CustomResponse.class);

I'd appreciate it if someone could explain what I'm doing wrong exactly so I can learn from it.

6
  • What is the error that you're getting? You're JSON contains an Object in the Error property, and not an Array
    – Folkert
    Aug 28 '18 at 15:23
  • Sorry I forgot to attach, I've updated my question now. Aug 28 '18 at 15:30
  • Do you have any examples of JSONs that contain actual errors?
    – Folkert
    Aug 28 '18 at 15:32
  • You are declaring the errors as list, whereas the attribute Errors in your JSON is not an array.
    – Jayant Das
    Aug 28 '18 at 15:33
  • 1
    You're JSON doesn't contain a list, but an object. It needs to change to {"isSuccess":true,"Errors":[{"123":"error code here"}, {"123":"error code here"}]}
    – Folkert
    Aug 28 '18 at 15:39
3

The wrapper class that you have expects an array of Errors as that's how you have declared it in your class as public List<CustomError> errors; which in turn has two attributes namely Id and error.

The JSON in that case should be something as below, so that when you deserialize the JSON, it maps back to your wrapper class.

{
  "IsSuccess":false,
  "Errors":[{"Id":"123", "error":"my error message"}]
}

If the Errrors attribute on the JSON itself is not expected to be an array, then you need to modify your wrapper class accordingly.

3
  • How can I correctly handle when Errors list is empty? Aug 28 '18 at 15:41
  • In that case, you should get that attribute in the response as "Errors":[]
    – Jayant Das
    Aug 28 '18 at 15:43
  • @DeploymentFailure you can omit it entirely (errors will be null), or use the null keyword ("errors":null, no quotes around null), or "errors":[], which would be a non-null empty list.
    – sfdcfox
    Aug 28 '18 at 15:47

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.