function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
vijaya kudupudivijaya kudupudi 

System.JSONException: Malformed JSON: Expected '{' at the beginning of object

I am getting System.JSONException: Malformed JSON: Expected '{' at the beginning of object exception when i am trying to call callouts in my test class. I used the link (https://developer.salesforce.com/blogs/developer-relations/2013/03/testing-apex-callouts-using-httpcalloutmock.html) to call callouts in my test class. Please Anybody can give solution.

 
Best Answer chosen by vijaya kudupudi
pconpcon
This is because your fakeResponse is not valid JSON.  You should say
 
SingleRequestMock fakeResponse1 = new SingleRequestMock(200,
                                                 'Complete',
                                                 '{"items": [{"Name": "sForceTest1"}]}',
                                                 null);

And in reality you should probably have more information in JSON since you get more data back than just the name.  Also, I would suggest that you deactivate that API key and generate a new one since you put your API key publicly on the internet.

All Answers

pconpcon
Can you provide the class that you wrote for the mock?  It sounds like your JSON data is not formatted correctly.

NOTE: When adding code please use the "Add a code sample" button (icon <>) to increase readability and make it easier to reference.
vijaya kudupudivijaya kudupudi
Hi pcon,

Thanks for your reply. Here is the code for mock.
//Controller class callout method
public List<WalmartItems> getwalitems(){
     //String url = 'http://api.walmartlabs.com/v1/search?query=ipod&format=json&categoryId=3944&apiKey=j6ew7b7wy3zx7cqu4cnwg3vv';
     String url = 'http://api.walmartlabs.com/v1/feeds/specialbuy?apikey=j6ew7b7wy3zx7cqu4cnwg3vv&categoryId=3944';
     HttpRequest req = new HttpRequest();
     req.setEndpoint(url);
     req.setMethod('GET');
     req.setTimeout(60000);
     Http http = new Http();
     HttpResponse res = http.send(req);
     String responseBody = res.getBody();
     system.debug('statuscode: ' + res.getStatusCode());
     
     ResCls resItems = (ResCls)JSON.deserialize(responseBody, ResCls.class);
     walitems = new List<WalmartItems>();
     List<Items> rl= resItems.Items;
     itemList = new List<Items>();
     for(Items it:rl){
         itemList.add(it);
         walitems.add(new WalmartItems(it));
     }

     return walitems;

 }

//mock callout

@isTest
public class SingleRequestMock implements HttpCalloutMock {
        protected Integer code;
        protected String status;
        protected String bodyAsString;
        protected Blob bodyAsBlob;
        protected Map<String, String> responseHeaders;

        public SingleRequestMock(Integer code, String status, String body,
                                         Map<String, String> responseHeaders) {
            this.code = code;
            this.status = status;
            this.bodyAsString = body;
            this.bodyAsBlob = null;
            this.responseHeaders = responseHeaders;
        }

        public SingleRequestMock(Integer code, String status, Blob body,
                                         Map<String, String> responseHeaders) {
            this.code = code;
            this.status = status;
            this.bodyAsBlob = body;
            this.bodyAsString = null;
            this.responseHeaders = responseHeaders;
        }

        public HTTPResponse respond(HTTPRequest req) {
            HttpResponse resp = new HttpResponse();
            resp.setStatusCode(code);
            resp.setStatus(status);
            if (bodyAsBlob != null) {
                resp.setBodyAsBlob(bodyAsBlob);
            } else {
                resp.setBody(bodyAsString);
            }

            if (responseHeaders != null) {
                 for (String key : responseHeaders.keySet()) {
                resp.setHeader(key, responseHeaders.get(key));
                 }
            }
            return resp;
        }
}

//Test class calling callouts part

 
    SingleRequestMock fakeResponse1 = new SingleRequestMock(200,
                                                 'Complete',
                                                 '[{"Name": "sForceTest1"}]',
                                                 null);

    Test.startTest();
    Test.setMock(HttpCalloutMock.class, fakeResponse1);
   // System.assertEquals('[{"Name": "sForceTest1"}]',fakeResponse1);
    qc.getSearchitems();

 
pconpcon
This is because your fakeResponse is not valid JSON.  You should say
 
SingleRequestMock fakeResponse1 = new SingleRequestMock(200,
                                                 'Complete',
                                                 '{"items": [{"Name": "sForceTest1"}]}',
                                                 null);

And in reality you should probably have more information in JSON since you get more data back than just the name.  Also, I would suggest that you deactivate that API key and generate a new one since you put your API key publicly on the internet.
This was selected as the best answer
vijaya kudupudivijaya kudupudi
Hi pcon,

Thank you for your reply. Now my code is covered, I got good code coveragre. Thanks for your suggestion.