-4

In the below code,method2 is calling twice.In the first call itsnt throwing any error but in second time call.It caues below error

Error: System.JSONException: Malformed JSON: Expected '[' at the beginning of List/Set

 List < WrapperCriteria > warpList = (List < WrapperCriteria > 
   )System.JSON.deserialize(wrapval, List<WrapperCriteria >.class);

<aura:component controller="ActionController"  implements="force:hasRecordId,force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:lightningQuickAction" access="global">
    <aura:attribute name="theId" type="String"/>
    <aura:attribute name="options" type="String[]"/>
    <aura:attribute name="wrplst" type="WrapperCriteria[]"/>
    <aura:attribute name="selectedValue" type="String"/>
    <aura:handler name="deleteJob" event="c:deleteJobEvt" action="{!c.RemoveClick}" />
    <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
    <p>
        <center><h5><b>Creating Action Criteria </b></h5></center>
    </p>
    <h3 class="slds-section-title--divider">
        <b>
            <I> Action Criteria</I>
        </b>
    </h3>
    <table >
        <tr class="slds-text-title--caps">
            <th class="head">
                <I>Action</I>
            </th>
            <th class="head">
                <I>Object Name</I>
            </th>
            <th class="head">
                <I>Component</I>
            </th>
            <th class="head">
                <I>Operator</I>
            </th>
            <th class="head">
                <I>Special Operator</I>
            </th>
            <th class="head">
                <I>Special Operator * Value</I>
            </th>
            <th class="head">
                <I>Special Operator / Value</I>
            </th>
        </tr>

        <aura:renderIf isTrue="{!v.wrplst.length > 0}">
            <p>wrapper Length:{!v.wrplst.length}</p>
           <aura:iteration items="{!v.wrplst}" var="a">
                <c:NewAction wrp="{!a}" options="{!v.options}" selectedValue=""  idval="{!v.theId}"/>
             </aura:iteration>
        </aura:renderIf>
    </table>
    <lightning:button variant="brand" label="Add row" onclick="{!c.AddRow}" />
    <lightning:button variant="brand"  label="Save" onclick="{!c.saveRow}" />
</aura:component>

    ({
    doInit: function(component, event, helper) {
        helper.pageLoad(component);
        helper.componentVal(component);

    },
    doSomething: function(component, event, helper) {
        helper.Method2(component);
    },
    RemoveClick: function(component, event, helper) {
        var selCont = event.getParam("selectedJob");
        var conts = component.get("v.wrplst");
        var contsval = JSON.stringify(conts);

        var Selndex = conts.indexOf(selCont);

        var DeleteLen = conts.length;
        //alert('deleteLen value::::' + DeleteLen);
        var removeAction=component.get("c.removeRow");
        removeAction.setParams({
            "wrvalue":contsval,
            "rowval":Selndex 
        });
        removeAction.setCallback(this, function(g) {
            var state = g.getState();
            if (state == 'SUCCESS') {
                alert('success value');
                component.set("v.wrplst",JSON.parse(g.getReturnValue()));
            }
            else if(state==='error'){
                alert('error value');
            }
        });
        $A.enqueueAction(removeAction);
    },
    AddRow: function(component, event, helper) {

        var comp1 = component.get("v.wrplst");
        var compJson1 = JSON.stringify(comp1);
        var mapRecords = new Array();
        for (i = 0; i < comp1.length; i++) {
            mapRecords.push(comp1[i]);
        }
        var len = mapRecords.length;

        var newlen = len + 1;

        var addAction = component.get("c.addRow");
        addAction.setParams({
            "wrapval": compJson1,
            "counterval": newlen,
        });
        addAction.setCallback(this, function(res) {
            var state = res.getState();
            if (state == 'SUCCESS') {
                component.set("v.wrplst", JSON.parse(res.getReturnValue()));
            } else if (state == 'ERROR') {
                alert('error');
            } else if (state == 'INCOMPLETE') {
                alert('incompltete');
            }
        });
        $A.enqueueAction(addAction);
    },
    saveRow: function(component, event, helper) {
        var Idx = component.get("v.theId");
        alert('Id value ::::' + Idx);
        var com = component.get("v.wrplst");
        var comJson = JSON.stringify(com);

        var saveAction = component.get("c.saveCall");
        saveAction.setParams({
            "wrvalue": comJson,
            "id": Idx,
        });
        saveAction.setCallback(this, function(re) {
            var state = re.getState();
            if (state === 'SUCCESS') {

            }
        });
        $A.enqueueAction(saveAction);
    }
});

    ({
    pageLoad: function(component, event) {
        var action = component.get("c.pageLoading");
        var self = this;
        var Idx = component.get("v.theId");
        action.setParams({
            "id": Idx
        });
        action.setCallback(this, function(g) {
            var state = g.getState();
            if (state == 'SUCCESS') {

                component.set("v.wrplst",JSON.parse(g.getReturnValue()));
                self.Method2(component);

            }
        });
        $A.enqueueAction(action);

    },

    Method2: function(component, event, helper) {

        var comp = component.get("v.wrplst");
        var compJson = JSON.stringify(comp);
        var Id1 = component.get("v.theId");
        var compAction = component.get("c.getComponent");  //First time method call its working fine
        compAction.setParams({
            "wrapval":compJson,
            "id": Id1,
        });
        compAction.setCallback(this, function(re) {
            var state = re.getState();
            if (state ==='SUCCESS') {
               var da=re.getReturnValue();
               var myJSON = re.getReturnValue();
               var myObj = JSON.stringify(myJSON);
                alert('myJson value:::::'+myObj);
               }
            else if(state==='error'){
                alert('error value');
            }
                else if(state==='INCOMPLETE'){
                    alert('incomplete values:::');

                }
        });
        $A.enqueueAction(compAction);
    },
    componentVal:function(component,event,helper){

        var action=component.get("c.ObjectNames");
        action.setCallback(this,function(re){
            var state=re.getState();
            if(state==='SUCCESS'){

                component.set("v.options",JSON.parse(re.getReturnValue()));
            }
            else if(state==='Error'){
                alert('error');
            }
        });
        $A.enqueueAction(action);
    }
})

second component:

<aura:attribute required="true" name="selectedValue" type="String"/>
<aura:attribute name="wpchange" type="List" />
<aura:registerEvent name="deleteJob" type="c:deleteJobEvt"/>

<tr>
    <td class="cell" style="padding-top:14px;padding-bottom:0px;">
        <p >
            <button type="button" onclick="{!c.RemoveClick}" >remove</button>
        </p>
    </td>
    <td class="cell" >
        <p>
          <lightning:select name="mySelect" label=" " value="{!v.wrp.ObjectApiNAme}" aura:id="obc" onchange="{!c.dosomething}">
            <aura:iteration items="{!v.options}" var="item">
                <option text="{!item.label}" value="{!item.value}" selected="{!item.selected}"/>
            </aura:iteration>
        </lightning:select> 
        </p>
    </td>
    <td class="cell" >

        <p>
            <lightning:select name="selectItem" label=" " value="{!v.wrp.Operator}">
                <aura:if isTrue="{!and(v.wrp.ObjectApiNAme!='Pay_Element_Master__c',
                             v.wrp.ObjectApiNAme!='CTC_Master__c', 
                              v.wrp.ObjectApiNAme!='Section_Master__c')}">
                <option value="None">None</option>
                    </aura:if>
               </lightning:select>
        </p>

    </td>

    <td class="cell" >
        <p>
            <lightning:select name="selectItem" label=" " value="{!v.wrp.Operator}">
                <option value="None">None</option>
                <option value="+ Addition">+ Addition</option>
                <option value="- Subtract  ">- Subtract</option>
                <option value="* Multiply ">* Multiply</option>
                <option value="/ Divide">/ Divide</option>
            </lightning:select>
        </p>
    </td>
    <td class="cell" >
        <p>
            <lightning:select name="selectItem" label=" " value="{!v.wrp.SpecialOperator}">
                <option value="None">None</option>
                <option value="*">*</option>
                <option value="*/">*/</option>
                <option value="/">/</option>
            </lightning:select>
        </p>
    </td>

    <td class="cell"  style="padding-top:14px;padding-bottom:0px;">
        <p>
            <ui:inputText value="{!v.wrp.specialOperatorValue}"/>
        </p>
    </td>
    <td class="cell"  style="padding-top:14px;padding-bottom:0px;">
        <p>
            <ui:inputText value="{!v.wrp.specialOperatorSlashValue}"/>
        </p>
    </td>
</tr>

({
    RemoveClick: function(component, event, helper) {

        var event1 = component.getEvent("deleteJob");

        event1.setParams({
            'selectedJob': component.get("v.wrp"),
        });
        event1.fire();
    },
    dosomething:function(component, event, helper) {
        var x=component.find("obc").get("v.value");
        alert('x value::::'+x);
        var comp = component.get("v.wrp");
        var compJson = JSON.stringify(comp);
        alert('compJson val ::::'+compJson);
        var Id1 = component.get("v.idval");
        alert('Id1 val::::::'+Id1);

        var Action = component.get("c.getComponent");  //second time call shows error in server side
        Action.setParams({
            "wrapval": compJson,
            "id": Id1,
        });
        Action.setCallback(this, function(re) {
            var state = re.getState();
            if (state ==='SUCCESS') {
                alert('sucess value :::');
               //Here Ive to set components value
               //components1 values as well
            }
            else if(state==='error'){
                alert('error value');
            }
                else if(state==='INCOMPLETE'){
                    alert('incomplete values:::');

                }
        });
        $A.enqueueAction(Action); 
    }
  })

server:

    public class ActionController
     {
@AuraEnabled
public static string pageLoading(string id) {

    List < Action_Criteria__c > RecordsInserted = new List < Action_Criteria__c > ();
    List < WrapperCriteria > wList = new List < WrapperCriteria > ();
    Criteria_Master__c cmas = new Criteria_Master__c();
    cmas=[select id, Name, Action_Criteria__c, Company_Master__c from Criteria_Master__c where Id =:id];
    RecordsInserted = [select id, Action_Criteria_API_Name__c, Action_Criteria_Field_Name__c, Criteria_Master__c, Object_API_Name__c, Operator__c, Object_Name__c, Special_Operator__c, Special_operator_slash_value__c, Special_operator_value__c from Action_Criteria__c where Criteria_Master__c = : id order by Sequence_No__c];
    system.debug('record Inserted values:::' + RecordsInserted);
    Integer counter=1;
    for (Action_Criteria__c ac: RecordsInserted) {
        WrapperCriteria wrp = new WrapperCriteria();
        wrp.record = ac;
        wrp.ObjectApiNAme = ac.Object_API_Name__c;
        wrp.FieldName = ac.Action_Criteria_API_Name__c;
        wrp.index =counter;
        counter=counter+1;
        wrp.CriteriaMasId = ac.Criteria_Master__c;
        wrp.Operator = ac.Operator__c;
        wrp.SpecialOperator = ac.Special_Operator__c;
        wrp.specialOperatorSlashValue = ac.Special_operator_slash_value__c;
        wrp.specialOperatorValue = ac.Special_operator_value__c;
        wList.add(wrp);
    }

    return JSON.serialize(wList);
}
@AuraEnabled
public static string ObjectNames()
{

    List<SelectOption> ObjNames= new List<SelectOption>();
    ObjNames.add(new SelectOption('','--None--'));
    ObjNames.add(new selectoption('Pay_Element_Master__c','Pay Element'));
    ObjNames.add(new selectoption('CTC_Master__c','CTC Master'));
    ObjNames.add(new selectoption('Section_Master__c','Section Master'));
    return JSON.serialize(ObjNames);
}

@AuraEnabled
public static string getComponent(string wrapval,string id) {
    String objectName;
    Criteria_Master__c cmas = new Criteria_Master__c();
    system.debug('iam calling');
    system.debug('id val:::::::'+id);

    //List < WrapperCriteria > warpList = (List < WrapperCriteria > )System.JSON.deserialize(wrapval, List<WrapperCriteria >.class);
    List < WrapperCriteria > warpList;
    try {
        warpList = (List < WrapperCriteria > )System.JSON.deserialize(wrapval, List<WrapperCriteria>.class); 
    } catch(Exception e) {
        WrapperCriteria warp = (WrapperCriteria)System.JSON.deserialize(wrapval, WrapperCriteria.class);
        warpList.add(warp);
     }
    system.debug('::::::wrList value::::' + warpList);
    system.debug('id value ::::::' + id);

     WrapperCriteria dc=new WrapperCriteria ();

    WrapperCriteria ac=new WrapperCriteria ();
    List < SelectOption > ObjNames = new List < SelectOption > ();
    ObjNames.add(new SelectOption('', '--None--'));
    ObjNames.add(new selectoption('Pay_Element_Master__c', 'Pay Element'));
    ObjNames.add(new selectoption('CTC_Master__c', 'CTC Master'));

    Map <String,String> ctcMasAPINames = new Map < String, String > ();
    cmas = [select id, Name, Action_Criteria__c, Company_Master__c from Criteria_Master__c where Id=:id];

    if (warpList.size() > 0) {
        for (WrapperCriteria wr: warpList) {
            List <SelectOption > options = new List <SelectOption > ();
            if (wr.ObjectApiNAme == 'Pay_Element_Master__c') {
                for (SelectOption so: ObjNames) {
                    if (so.Value == wr.ObjectApiNAme) {
                        objectName = so.Label;
                        system.debug('****objectname *****' + objectName);
                    }
                }
                system.debug('wr.SelObjectName value ::::::'+ wr.SelObjectName);
                system.debug('object name:::::::::::::'+objectName);
                try{
                    if(wr.SelObjectName==null){
                       wr.SelObjectName = objectName;                          
                }
                }catch (exception e){
                    system.debug('e value'+e);
                }




                for (Pay_Element_Master__c pem: [select id, name, Company_Master__c from Pay_Element_Master__c where Company_Master__c = : cmas.Company_Master__c]) {
                    options.add(new SelectOption(pem.id, pem.name));
                    //dc.componentMap.put(pem.id,pem.name);
                    ctcMasAPINames.put(pem.id, pem.name);
                    System.debug('--------Pay element MAster MAP VAlues-----' + ctcMasAPINames);
                }
                ac.Components = options;
                system.debug('ac.Components value:::::::'+ac.Components);
            } 
            else if (wr.ObjectApiNAme == 'CTC_Master__c') {
                for (SelectOption so: ObjNames) {
                    if (so.Value == wr.ObjectApiNAme) {
                        objectName = so.Label;
                        system.debug('-----------objectname --------------' + objectName);
                    }
                }
                wr.SelObjectName = objectName;
                Map < String, Schema.SObjectType > globalDescription = Schema.getGlobalDescribe();
                Schema.sObjectType objType = globalDescription.get('CTC_Master__c');
                Schema.DescribeSObjectResult ob = objType.getDescribe();

                if (ob == Null) {
                    AuraHandledException e = new AuraHandledException('Invalid sObject Type');
                    e.setMessage('Invalid sObject Type');
                    system.debug(e);
                    throw e;

                }
                Map < String, Schema.SObjectField > mapFieldList = ob.fields.getMap();

                for (Schema.SObjectField field: mapFieldList.values()) {
                    Schema.DescribeFieldResult fieldResult = field.getDescribe();
                    if (fieldResult.isAccessible() && (fieldResult.getType() == Schema.DisplayType.Integer || fieldResult.getType() == Schema.DisplayType.Double || fieldResult.getType() == Schema.DisplayType.Currency)) {
                        options.add(new SelectOption(fieldResult.getName(), fieldResult.getLabel()));
                        //dc.componentMap1.put(fieldResult.getName(),fieldResult.getLabel());
                        ctcMasAPINames.put(fieldResult.getName(),fieldResult.getLabel());   
                    }
                }
                ac.Components1= options;
                system.debug('ac.Components1 value:::::::'+ac.Components1);
            }
        }
    }
    system.debug('ac ::::::value :::::'+ac);
    return JSON.serialize(ac);

}


@AuraEnabled
public static string addRow(string wrapval,integer counterval ){
    system.debug('counter value::::'+counterval);
    List < WrapperCriteria > warpList = (List<WrapperCriteria >)JSON.deserialize(wrapval,List<WrapperCriteria >.class);

    WrapperCriteria objInnerClass = new WrapperCriteria();
    Action_Criteria__c newAc= new Action_Criteria__c();        
    objInnerClass.record = newAc;
    objInnerClass.index = counterval;
    warpList.add(objInnerClass);    
    system.debug('------warpList---->'+warpList); 
    return JSON.serialize(warpList);
}
@AuraEnabled
public static void saveCall(string wrvalue,string id){
    List<Action_Criteria__c> RecordsToBeInserted=new List<Action_Criteria__c>();
    Map <String,String> ctcMasAPINames = new Map < String, String > ();
    system.debug('save functionality is calling::::');
    List < WrapperCriteria > warpList = (List < WrapperCriteria >) JSON.deserialize(wrvalue, List<WrapperCriteria >.class);
    system.debug('::::::::::::warpList::::::::::::::::'+warpList);
    system.debug('id value:::::::::::'+id);
    List<Criteria_Master__c> updatedCrimasters=new List<Criteria_Master__c>();
    Criteria_Master__c cmas = new Criteria_Master__c();

    cmas=[select id, Name, Action_Criteria__c, Company_Master__c from Criteria_Master__c where Id =:id];
    ID cid=cmas.id;
    system.debug('cid value ::::::'+cid);

    if(warpList!=null && !warpList.isEmpty())
    {
        for(WrapperCriteria wf: warpList)
        {
            system.debug('wrapper calling::::::::::::::::::::');
           // if(!string.isBlank(wf.SelObjectName) && !string.isBlank(wf.FieldName))
            //{    
                Action_Criteria__c ac= wf.record;
                ac.Criteria_Master__c =cid ;
                ac.Object_Name__c=wf.SelObjectName;
                if(wf.Operator!='None')
                {
                    ac.Operator__c=wf.Operator;
                }
                ac.Object_API_Name__c=wf.ObjectApiNAme;
                ac.Action_Criteria_API_Name__c=wf.FieldName;
                ac.Special_operator_slash_value__c = wf.specialOperatorSlashValue;
                ac.Special_operator_value__c = wf.specialOperatorValue;
                // System.debug('-----fc.object api--------'+ctcMasAPINames.ContainsKey(wf.FieldName));
                if(ctcMasAPINames.ContainsKey(wf.FieldName)) 
                {
                    if(ac.Object_API_Name__c=='Pay_Element_Master__c')
                    {
                        ac.Action_Criteria_Field_Name__c= ctcMasAPINames.get(wf.FieldName);
                    }
                    if(ac.Object_API_Name__c=='CTC_Master__c')
                    {
                        ac.Action_Criteria_Field_Name__c= ctcMasAPINames.get(wf.FieldName);
                        System.debug('-------------'+ctcMasAPINames.get(wf.FieldName));
                    }

                }
                system.debug('==fc==>'+ac);
                RecordsToBeInserted.add(ac);

            //}
        }

        system.debug('==RecordsToBeInserted==>'+RecordsToBeInserted.size());
        upsert RecordsToBeInserted;
        for(Criteria_Master__c cm:[select id,Name,Filter_Criteria__c from Criteria_Master__c where Id=:id])
        {
            string ActionCriteria;
            if(!RecordsToBeInserted.isEmpty())
            {
                for(Action_Criteria__c ac: [select id, Object_API_Name__c,Action_Criteria_API_Name__c, Sequence_No__c, Operator__c, Criteria_Master__c from Action_Criteria__c where Criteria_Master__c=:id order by  Sequence_No__c asc])
                {
                    if(string.isBlank(ActionCriteria))
                    {
                        ActionCriteria =  string.valueof(ac.Action_Criteria_API_Name__c);
                    }
                    else
                    {
                        ActionCriteria =  ActionCriteria + string.valueof(ac.Action_Criteria_API_Name__c);
                    }
                    if(ac.Operator__c=='+ Addition')
                    {
                        ActionCriteria = ActionCriteria +'+';    
                    }
                }
                if(!string.isBlank(ActionCriteria))
                {
                    cm.Action_Criteria_Logic__c =  ActionCriteria;
                }
                cm.Action_Criteria__c =True;
                updatedCrimasters.add(cm);
            }
        }
        update updatedCrimasters;
        system.debug('update criteria master::::::::::'+updatedCrimasters);
    }
}
@AuraEnabled
public static string removeRow(string wrvalue,integer rowval){
    system.debug('::::: rowToRemove val  :::::'+rowval);

    List < WrapperCriteria > warpList = (List < WrapperCriteria > ) JSON.deserialize(wrvalue, List<WrapperCriteria >.class);
    system.debug('::::::wrList value::::' + warpList);
    rowval = Integer.valueOf(rowval);
    if(!string.isBlank(string.valueof(rowval)))
    {
        Action_Criteria__c acdelete = warpList[rowval].record;
        list<Action_Criteria__c> listAc = new list<Action_Criteria__c>();

        if(!string.isblank(acdelete.id))
        {
            Criteria_Master__c criteriaMaster = [select id,Name,Action_Criteria__c,(select id, Criteria_Master__c from Action_Criteria__r where id!=:acdelete.id ) from Criteria_Master__c where Id=:acdelete.Criteria_Master__c];
            listAc = [select id, Criteria_Master__c from Action_Criteria__c where id!=:acdelete.id and Criteria_Master__c=:acdelete.Criteria_Master__c];
            if(criteriaMaster.Action_Criteria__r.isEmpty())
            {
                criteriaMaster.Action_Criteria__c = false;
                update criteriaMaster;
            }
            delete acdelete;
        }
    }
    warpList.remove(rowval);
    system.debug('wraper List  *******'+warpList);
    return JSON.serialize(warpList);
} 

}

0

Hi Annappa in your code for the first time you are passing list of your wrapperclass and you deserialize as a list that is correct. but for the seconde time you passing sing wrapperclass object you are trying to deserialize to a list so i think beacuse of that you getting error. so try the below code.

       List < WrapperCriteria > warpList = new List < WrapperCriteria >();
       try {
            warpList = (List < WrapperCriteria > )System.JSON.deserialize(wrapval, List<WrapperCriteria>.class); 
       } catch(Exception e) {
            WrapperCriteria warp = (WrapperCriteria)System.JSON.deserialize(wrapval, WrapperCriteria.class);
            warpList.add(warp)
       }

And i believe you defined wrp attribute in your component type as WrapperCriteria.

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.