0

No idea what I'm doing, but I'm getting the following error for a VisualForce page:

Malformed JSON: Expected '{' at the beginning of object Error is in expression '{!confirmOrder}' in component in page adt_apis: Class.System.JSONParser.readValueAs: line 117, column 1 Class.ADTConfirmOrder.confirmOrder: line 83, column 1

Here's the entire code for the VFP:

<apex:page showHeader="false" 
        sidebar="false" 
        standardStylesheets="true"
        standardController="Account" 
        extensions="ADTCreateUpdateOrder,ADTConfirmOrder,ADTGetStatus,ADTCreateContract,ADTGetSigningURL,ADTGetOrderDetails">
<!-- fields to access in the controller -->
<apex:pageBlock rendered="false" 
                mode="detail">
        <apex:outputText value="{!Account.Order_ID__c}"/>
</apex:pageBlock>
<apex:outputPanel id="all"  style="overflow:auto;width:750px;height:250px">
    <apex:actionStatus id="sendRequest">
        <apex:facet name="stop">
            <apex:form >
                <apex:pageMessages />
                <apex:outputPanel rendered="{!AND(NOT(hasSuccessfuladtCreateUpdateOrder),accountHasAllRequiredFields)}">
                    <apex:pageBlock title="Send to ADT">
                        <apex:pageMessage rendered="{!adtCreateUpdateOrders.size=0}" severity="Info" strength="3" summary="No Order Creations on File" detail="Please submit a request to the ADT Service."/>
                        <apex:pageBlockButtons location="bottom">
                            <apex:commandButton value="Create/Update Order"
                                                status="sendRequest" 
                                                action="{!CreateUpdateOrder}" 
                                                rerender="all"/>
                        </apex:pageBlockButtons>
                        <apex:pageBlockSection rendered="{!adtCreateUpdateOrders.size>0}" columns="1">
                            <apex:pageMessage severity="Warning" strength="3" summary="Order creation request(s) have not been successful." detail="Please see the ADT Create Update Order record(s) for details."/>
                            <apex:pageBlockSection rendered="{!adtCreateUpdateOrders.size>0}"  title="Create Update Order(s):">
                                <apex:pageBlockTable value="{!adtCreateUpdateOrders}" var="ADTCreateUpdateOrder">
                                    <apex:column >
                                        <apex:outputLink target="_parent" value="/{!ADTCreateUpdateOrder.Id}">{!ADTCreateUpdateOrder.Name}</apex:outputLink>
                                    </apex:column>
                                    <apex:column value="{!ADTCreateUpdateOrder.Success__c}"/>
                                </apex:pageBlockTable>
                            </apex:pageBlockSection>
                           <apex:pageBlockSection rendered="{!adtConfirmOrders.size>0}" title="Confirm Order(s)"> 
                                <apex:pageBlockTable value="{!adtConfirmOrders}" var="ADTConfirmOrder">
                                    <apex:column >
                                        <apex:outputLink target="_parent" value="/{!ADTConfirmOrder.Id}">{!ADTConfirmOrder.Name}</apex:outputLink>
                                    </apex:column>
                                    <apex:column value="{!ADTConfirmOrder.Success__c}"/>
                                </apex:pageBlockTable>
                            </apex:pageBlockSection>
                          <apex:pageBlockSection rendered="{!adtGetOrderDetails.size>0}"  title="Order Detail(s):">
                                <apex:pageBlockTable value="{!adtGetOrderDetails}" var="ADTGetOrderDetail">
                                    <apex:column >
                                        <apex:outputLink target="_parent" value="/{!ADTGetOrderDetail.Id}">{!ADTGetOrderDetail.Name}</apex:outputLink>
                                    </apex:column>
                                    <apex:column value="{!ADTGetOrderDetail.Success__c}"/>
                                </apex:pageBlockTable>
                            </apex:pageBlockSection>
                        </apex:pageBlockSection>
                    </apex:pageBlock>
                </apex:outputPanel>
                <apex:pageBlock rendered="{!hasSuccessfuladtCreateUpdateOrder}">
                    <apex:pageBlockButtons location="bottom">
                        <apex:commandButton value="Get Status"
                                            status="sendRequest" 
                                            action="{!GetStatus}" 
                                            rerender="all"
                                            rendered="{!NOT(hasSuccessfuladtGetStatus)}"/>
                        <apex:commandButton value="Create Contract"
                                            status="sendRequest" 
                                            action="{!createContract}" 
                                            rerender="all"
                                            rendered="{!AND(hasSuccessfuladtGetStatus,!hasSuccessfuladtCreateContract)}"/>
                        <apex:commandButton value="Confirm Order"
                                            status="sendRequest" 
                                            action="{!confirmOrder}" 
                                            rerender="all"
                                            rendered="{!(AND(hasSuccessfuladtCreateContract,!hasSuccessfuladtConfirmOrder,$Profile.Name != 'Sales'),TRUE,FALSE)}"/>
                        <apex:commandButton value="Order Details"
                                            status="sendRequest" 
                                            action="{!GetOrderDetails}" 
                                            rerender="all"
                                            rendered="{!IF(AND(hasSuccessfuladtCreateContract,hasSuccessfuladtConfirmOrder,$Profile.Name != 'Sales'),TRUE,FALSE)}" />
                        <apex:commandButton value="Update Order"
                                            status="sendRequest" 
                                            action="{!CreateUpdateOrder}" 
                                            rerender="all"/>
                    </apex:pageBlockButtons>
                    <apex:pageBlockSection title="Create Update Order(s):" columns="1">
                        <apex:pageBlockTable value="{!adtCreateUpdateOrders}" var="ADTCreateUpdateOrder">
                            <apex:column >
                                <apex:outputLink target="_parent" value="/{!ADTCreateUpdateOrder.Id}">{!ADTCreateUpdateOrder.Name}</apex:outputLink>
                            </apex:column>
                            <apex:column value="{!ADTCreateUpdateOrder.Success__c}"/>
                        </apex:pageBlockTable>
                    </apex:pageBlockSection>
                    <apex:pageBlockSection rendered="{!adtGetStatuses.size>0}" title="Get Status(es)" columns="1">
                        <apex:pageBlockTable value="{!adtGetStatuses}" var="adtGetStatus">
                            <apex:column >
                                <apex:outputLink target="_parent" value="/{!adtGetStatus.Id}">{!adtGetStatus.Name}</apex:outputLink>
                            </apex:column>
                            <apex:column value="{!adtGetStatus.Instruction__c}"/>
                        </apex:pageBlockTable>
                    </apex:pageBlockSection>
                    <apex:pageBlockSection rendered="{!AND(hasSuccessfuladtGetStatus,adtCreateContracts.size=0)}" title="ADT Create Contract Settings" columns="2">
                        <apex:pageBlockSectionItem >
                            <apex:outputLabel value="{!$ObjectType.Account.fields.Signing_Method__c.Label}"/>
                        </apex:pageBlockSectionItem>
                        <apex:pageBlockSectionItem >
                            <apex:actionRegion >
                                <apex:inputField value="{!Account.Signing_Method__c}">
                                    <apex:actionSupport event="onchange" rerender="all" status="sendRequest" action="{!updateAccount}"/>
                                </apex:inputField>
                            </apex:actionRegion>
                        </apex:pageBlockSectionItem>
                    </apex:pageBlockSection>
                    <apex:pageBlockSection rendered="{!adtCreateContracts.size>0}" title="Create Contract(s)" columns="2">
                        <apex:pageBlockSectionItem >    
                            <apex:pageBlockTable value="{!adtCreateContracts}" var="adtCreateContract">
                                <apex:column >
                                    <apex:outputLink target="_parent" value="/{!adtCreateContract.Id}">{!adtCreateContract.Name}</apex:outputLink>
                                </apex:column>
                                <apex:column value="{!adtCreateContract.Success__c}"/>
                            </apex:pageBlockTable>
                        </apex:pageBlockSectionItem>
                        <apex:pageBlockSectionItem >
                            <apex:outputLabel value="{!$ObjectType.Account.fields.Signing_Method__c.Label}"/>
                            <apex:actionRegion >
                                <apex:inputField value="{!Account.Signing_Method__c}">
                                    <apex:actionSupport event="onchange" rerender="all" status="sendRequest" action="{!updateAccount}"/>
                                </apex:inputField>
                            </apex:actionRegion>
                        </apex:pageBlockSectionItem>
                    </apex:pageBlockSection>
                    <apex:pageBlockSection rendered="{!hasSuccessfuladtGetSigningURL}" title="Get Signing URL(s)" columns="1">
                        <apex:pageBlockTable value="{!ADTGetSigningURLs}" var="ADTGetSigningURL">
                            <apex:column >
                                <apex:outputLink target="_parent" value="/{!ADTGetSigningURL.Id}">{!ADTGetSigningURL.Name}</apex:outputLink>
                            </apex:column>
                            <apex:column value="{!ADTGetSigningURL.URL__c}"/>
                        </apex:pageBlockTable>
                    </apex:pageBlockSection>
                    <apex:pageBlockSection rendered="{!adtConfirmOrders.size>0}" title="Confirm Order(s)" columns="1">
                        <apex:pageBlockTable value="{!adtConfirmOrders}" var="ADTConfirmOrder">
                            <apex:column >
                                <apex:outputLink target="_parent" value="/{!ADTConfirmOrder.Id}">{!ADTConfirmOrder.Name}</apex:outputLink>
                            </apex:column>
                            <apex:column value="{!ADTConfirmOrder.Success__c}"/>
                        </apex:pageBlockTable>
                    </apex:pageBlockSection>
               <apex:pageBlockSection rendered="{!adtGetOrderDetails.size>0}" title="Order Detail(s)" columns="1">
                        <apex:pageBlockTable value="{!adtGetOrderDetails}" var="ADTGetOrderDetail">
                            <apex:column >
                                <apex:outputLink target="_parent" value="/{!ADTGetOrderDetail.Id}">{!ADTGetOrderDetail.Name}</apex:outputLink>
                            </apex:column>
                            <apex:column value="{!ADTGetOrderDetail.Success__c}"/>
                        </apex:pageBlockTable>
                    </apex:pageBlockSection>
                </apex:pageBlock>
            </apex:form>
        </apex:facet>
        <apex:facet name="start">
            <img src="{!URLFOR($Resource.vWork,'images/ProgressBar.gif')}"/>
        </apex:facet>
    </apex:actionStatus>
</apex:outputPanel>

public class ADTConfirmOrder{
private final Account a;
public ADTConfirmOrder(ApexPages.StandardController stdController){
    a=(Account)stdController.getRecord();
}
public ADT_Confirm_Order__c[] adtConfirmOrders{
    get{
        ADT_Confirm_Order__c[] adtConfirmOrders = new ADT_Confirm_Order__c[]{};
        for(ADT_Confirm_Order__c adtConfirmOrder : [SELECT Name,Success__c FROM ADT_Confirm_Order__c WHERE Account__c=:a.Id])
            adtConfirmOrders.add(adtConfirmOrder);
        return adtConfirmOrders;
    }
    set;
}
public Boolean hasSuccessfuladtConfirmOrder {
    get{
        Boolean hasSuccessfuladtConfirmOrder = false;
        for(ADT_Confirm_Order__c adtConfirmOrder : adtConfirmOrders) 
            if(adtConfirmOrder.Success__c)
                hasSuccessfuladtConfirmOrder=true;
        return hasSuccessfuladtConfirmOrder;
    }
    set;
}
public void confirmOrder(){
    ADT_Create_Update_Order__c adtCreateUpdateOrder = (ADT_Create_Update_Order__c) Database.Query('SELECT Id FROM ADT_Create_Update_Order__c WHERE Success__c = TRUE AND Account__c = \'' + a.Id +'\' LIMIT 1');
    HttpRequest req = new HttpRequest();
    req.setEndpoint(ADTConfirmOrder__c.getValues('Endpoint').Value__c);
    req.setMethod('POST');
    req.setheader('Content-type', 'application/json');
    req.setheader('Authorization', 'Basic ' + EncodingUtil.base64Encode(blob.valueOf(ADTConfirmOrder__c.getValues('Username').Value__c+':'+ADTConfirmOrder__c.getValues('Password').Value__c)));
    req.setTimeout(120000);
    JSONGenerator gen = JSON.createGenerator(true);
    try{
          gen.writeStartObject();
            gen.writeFieldName(ADTConfirmOrder__c.getValues('requestObject').Value__c);
            gen.writeStartObject();
                gen.writeNumberField('masterDealerNumber',Integer.ValueOf(ADTConfirmOrder__c.getValues('masterDealerNumber').Value__c));
                gen.writeStringField('orderID',a.getPopulatedFieldsAsMap().containsKey(ADTConfirmOrder__c.getValues('orderID').Value__c)?(String)a.get(ADTConfirmOrder__c.getValues('orderID').Value__c):'');
            gen.writeEndObject();
        gen.writeEndObject();
    }catch(Exception e){
        system.debug(   'The request could not be preparred by Apex.'+
                        ' \n There was a(n) '+e.getTypeName()+
                        ' type of error stating: \n"'+e.getMessage()+
                        '"\n on line '+e.getLineNumber()+
                        ' when running:  \n'+e.getStackTraceString()+
                        '\n We sent ADT: '+gen.getAsString());
    }
    req.setBody(Test.isRunningTest() ? 'Test Request' :  gen.getAsString());
    req.setHeader('Content-Length',String.ValueOf(Blob.ValueOf(req.getBody()).size()));
    //must store response as string or Response__c will truncate
    String response = new Http().send(req).getBody();
    Map<String, Object> deserializedResponse = (Map<String, Object>)JSON.deserializeUntyped(response);
    Id adtConfirmOrder = Database.Insert(new   ADT_Confirm_Order__c(Account__c=a.Id,
                                                                    ADT_Create_Update_Order__c=adtCreateUpdateOrder.Id,
                                                                    Body__c=req.getBody(),
                                                                    Endpoint__c=req.getEndpoint(),
                                                                    Content_Type__c=req.getHeader('Content-type'),
                                                                    Method__c=req.getMethod(),
                                                                    Response__c=response,
                                                                    Success__c=!deserializedResponse.containsKey('errors'))).getId();
    if(deserializedResponse.containsKey('errors'))
        try{
            List<Object> errorObject = (List<Object>)deserializedResponse.get('errors');
            Map<String, Object> errors = (Map<String, Object>)errorObject[0];
            Database.Insert(new ADT_Confirm_Order_Error__c( ADT_Confirm_Order__c=adtConfirmOrder,
                                                            Status__c=Integer.ValueOf((String)errors.get('status')),
                                                            Error_Code__c=(String)errors.get('errorCode'),
                                                            Error_Message__c=(String)errors.get('errorMessage')));
        }catch(Exception e){
            ApexPages.addMessage(new ApexPages.Message(ApexPages.severity.Error, 'Problem creating ADT_Confirm_Order_Error__c record: '+e.getMessage()));
        }
    else{
        JSONParser parser = JSON.createParser(response);
        parser.nextToken();
        parser.nextToken();
        parser.nextToken();
        confirmOrderResponse cOR = (confirmOrderResponse)parser.readValueAs(confirmOrderResponse.class);
        Database.Update(new ADT_Confirm_Order__c(  Id=adtConfirmOrder,
                                                    orderID__c = cOR.orderID,
                                                    statusCode__c = cOR.statusCode
                                                   ));
    }
}
public class confirmOrderResponse{
    public String orderID;
   public String statusCode;

}

}

  • 2
    You will also need to post at least the Apex ADTConfirmOrder.confirmOrder method. – Keith C Nov 9 '17 at 21:26
  • 1
    If you know the JSON string that you're trying to parse (say, by including it in a system.debug(); call and pulling it from your execution log), that would also be helpful. The error here is pretty straightforward, you'll just need to follow the code until you find the source of the issue (i.e. the error says line X is the issue, and you find the data that feeds that line comes from method Y, which gets its data from Class Z, etc...) – Derek F Nov 9 '17 at 21:31
  • I just added the Apex Class – Eddie P Nov 9 '17 at 21:33
  • I can't figure it out... Still getting the error if anyone can help – Eddie P Nov 9 '17 at 22:57
  • What is the JSON that is returned? A blind guess here, but I wonder if you have too many nextToken() calls and you're blowing past the beginning of the inner JSON object. – ArtieBrosius Nov 10 '17 at 4:08
0

What is the JSON that is returned? A blind guess here, but I wonder if you have too many nextToken() calls and you're blowing past the beginning of the inner JSON object.

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.