0

Malformed JSON: Expected '{' at the beginning of object

@HttpPost   


    global static Void doPost() 
    {            
        //Initailizing variables
        String respString ='';
        RestRequest req = RestContext.request;
        RestResponse resp = RestContext.response;
        res.addHeader('Content-Type', 'application/json');
        Response repObj = new Response();

       Test_Survey__c surveyobj = new Test_Survey__c();
      try
      {
      RequestJSON reqData = new RequestJSON();
      Boolean  flag = False;


     reqData = (RequestJSON)JSON.deserialize(req.requestBody.toString(),RequestJSON.class);        
     flag = validate();   
     String Duprec = CheckDuplicateSurvey(reqData.Mobile_1);
    // System.debug('after validate '+Duprec);
     if(String.IsNOtBlank(Duprec))
     {
     String  Error= 'Duplicate Mobile No';
     resp.responseBody = Blob.valueOf(Error);                 
     }


     if(String.IsBlank(Duprec))
     {

      if(!flag){       
        // logic Part

       surveyobj.Test_Mobile_1__c=reqData.Mobile_1;
       surveyobj.Test_Mobile_2__c=reqData.Mobile_2;
       surveyobj.Test_Whats_App_Number__c=reqData.Whats_App_Number;
       surveyobj.Test_LandLine__c=reqData.LandLine;

        surveyobj.Test_State__c=reqData.State;             
        surveyobj.Test_District__c=reqData.District;
        surveyobj.Test_Taluka__c=reqData.Taluka;       
        surveyobj .Test_Hamlet_Segment_Camp__c = reqData.Hamlet_Segment_Camp;                                        

        surveyobj.Test_Supervisor_Name__c=reqData.Supervisor_Name;
        surveyobj.Test_Respondent_Name__c=reqData.Respondent_Name;      
        insert surveyobj;  


          repObj.Success = true;
          repObj.ResponseCode = '200';
          repObj.Message = 'New Survey Created';
          repObj.surveylist= new List<Test_Survey__c>();        

        String tempdata = JSON.serialize(repObj);
        resp.responseBody = Blob.valueOf(tempdata); 
        respString = JSON.serializePretty(repObj,false);



      }

      else{

          repObj.Success = false;
          repObj.ResponseCode = '400';
          repObj.Message = 'Survey Not Created';

        String tempdata = JSON.serialize(repObj, false);
        resp.responseBody = Blob.valueOf(tempdata); 
        respString = JSON.serializePretty(repObj,false);

        resp.responseBody = Blob.valueOf(respString);


      }


      }else{
      repObj.Success = false;
          repObj.ResponseCode = '400';
          repObj.Message = 'Found Duplicate Mobile No';

        String tempdata = JSON.serialize(repObj, false);
        resp.responseBody = Blob.valueOf(tempdata); 
        respString = JSON.serializePretty(repObj,false);        
        resp.responseBody = Blob.valueOf(respString);


     }

      }//end of try
      Catch(Exception e){

            resp.responseBody = Blob.valueOf('Error has occurred.');

        }//end of catch



    }//end of Post method

Test Class

 static testMethod void doPost() {

       Test.startTest(); 
        String json = '{  '+
        '   \"Test_Mobile_1\":\"7978445691\",'+
        '   \"Test_Mobile_2\":\"7978445691\",'+
        '   \"Test_Whats_App_Number\":\"7978445691\",'+
        '   \"Test_LandLine\":\"022-240456320\",'+
        '   \"Test_State\":\"Karnataka\",'+
        '   \"Test_District\":\"Mysore\",'+
        '   \"Test_Taluka\":\"Mysore\",'+
        '   \"Test_Hamlet_Segment_Camp\":\"cxsfdsf\",'+
        '   \"Test_DOBOfFamilyHead\":\"2017-06-03T10:34:24.000Z\",'+
        '   \"Test_Do_you_have_your_own_house\":\"Yes\",'+
        '   \"Test_No_of_HouseuownHouseCharacteristics\":\"1\",'+
        '   \"Test_Field_Investigator_Name\":\"xyz\",'+
        '   \"Test_Supervisor_Name\":\"Supervisor 1\",'+
        '   \"Test_Respondent_Name\":\"Respondent 2\",'+
        '   \"Test_Date_of_the_survey\":\"2017-06-03\",'+
        '   \"Test_Agent_Mobile_No\":\"7978445697\",'+
        '   \"Test_Survey_Date\":\"2018-06-03T10:34:24.000Z\",'+
        '   \"Test_Solution_Date\":\"2018-06-03T10:34:24.000Z\",'+
        '   \"Test_Aspiration_for_new_house_const\":\"Yes\",'+
        '   \"Test_Main_occupation_of_the_family\":\"Employed\",'+
        '   \"Test_Problems_faced_by_the_Family\":\"Wealth\",'+
        '   \"Test_Consent_Status\":\"Consent For Interview\",'+
        '   \"Test_Family_Owns_Loan\":\"Yes\",'+
        '   \"Test_Loan_Amount\":\"750000\",'+
        '   \"Test_Balance_loan_amount_Outstanding\":\"75000\",'+
        '   \"Test_Do_you_want_remedy\":\"Yes\",'+
        '   \"Test_when_do_you_want\":\"2017-06-03\",'+
        '   \"Test_Remarks\":\"Good\"'+
        '}';



        RestRequest req = new RestRequest();    
        req.addHeader('Content-Type', 'application/json');            
        req.requestUri ='/services/apexrest/CreateHH_Survey/';
        req.httpMethod = 'POST';
        req.requestBody= Blob.valueOf(json);
        RestContext.request = req;

        Create_HH_Survey.doPost();

        RestResponse res = new RestResponse();
        RestContext.response = res;
       Create_HH_Survey.Response repObj = new Create_HH_Survey.Response();

        System.assertEquals(true,repObj.Success);  
         System.assertEquals('200',repObj.ResponseCode);  
         System.assertEquals('New Survey Created',repObj.Message);  
         System.assert(repObj!= null);
         Test.StopTest();
    }  
  • P.S. you don't need to escape quotation marks (\") in Apex code, because they do not terminate string sequences. – sfdcfox Feb 8 at 16:34
0

Use object and then JSON.stringify(your Object) .

  • 1
    This answer is rather short. Could you please edit it to include more details? I'm also not sure how this addresses the issue in the question (after just a quick glance). High-quality answer usually go into detail about what the original problem is, why it's a problem, how to fix it, and why the fix works. – Derek F Feb 8 at 12:37
  • @DerekF FYI, the technique referred to is one I use myself, but yes, this answer could be expanded to be useful. – sfdcfox Feb 8 at 16:46
  • i am getting Error Malformed JSON: Expected '{' at the beginning of object – user63974 Feb 11 at 5:03
0

The answer to:

How to Pass 'Content-Type', 'application/json' in Test Method

is to use this addHeader method:

RestRequest req = new RestRequest();  
req.addHeader('Content-Type', 'application/json');            
req.requestUri ='/services/apexrest/CreateHH_Survey/';

but your NullPointerException is unlikely to be caused by that being missing. Check the line numbers in the stack trace to figure that out.

  • I i Have Added Content Header but getting System.JSONException: Malformed JSON: Expected '{' at the beginning of object – user63974 Feb 8 at 12:49

Your Answer

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