0

I need to convert javascript code into JSON. I am passing list from apex class and i want to convert that wrapper into JSON in below format.

    {

    "recordtype":"salesorder",
     "department":"19",
     "entity":"128940",
     "custbody_ava_shiptousecode":"1",
      "items":[{
                "item":"15550",
                "description": "",
                "quantity":"10",
                "amount":"35000",
                "custcol_term":"",
                "custcol_total_price":""
                
                
},
{
                "item":"15550",
                "description": "",
                "quantity":"10",
                "amount":"35000",
                "custcol_term":"",
                "custcol_total_price":""


}
]

}

Items[] array can be multiple

.

With the help of below code i am able to obtain below output:

{
  "recordtype": "salesorder",
  "department": "19",
  "entity": "128940",
  "items": [
    {
      "item": "14076"
    },
    {
      "description": ""
    },
    {
      "quantity": "200.00"
    },
    {
      "amount": "36000.00"
    },
    {
      "item": "14087"
    },
    {
      "description": ""
    },
    {
      "quantity": "1.00"
    },
    {
      "amount": "2500.00"
    },
    {
      "item": "14084"
    },
    {
      "description": ""
    },
    {
      "quantity": "1.00"
    },
    {
      "amount": "500.00"
    }
  ]
}

But i am not getting items as an seperate array.

JS controller--

var action2 = component.get("c.createOrderInNs");
        var result;
        var orderItmList;
        var itemArray = [];
        var nsCustomerId;
        action2.setParams({"quoteId" : component.get("v.recordId") }); 
        action2.setCallback(this, function(response) {
            if (response.getState() === "SUCCESS") {
                
                result = response.getReturnValue();
                orderItmList = JSON.stringify(result);
                console.log('orderItmList '+orderItmList);
                var itemWrapList = [];
                var fidWrapArr = [];
                var itemWrapArr = [];
                result.forEach(function (element){
                    if(!$A.util.isEmpty(element.fidWrap)){
                        fidWrapArr.push(element.fidWrap);
                    }
                    if(!$A.util.isEmpty(element.itemWrapLst)){
                        itemWrapList.push(element.itemWrapLst);    
                        
                    }
                    nsCustomerId = element.customerId;
                },this);
                console.log('itemWrapList '+JSON.stringify(itemWrapList));
                itemWrapList.forEach(function (element){   
                    for(var i=0;i<element.length;i++){
                        console.log(element.length);
                        console.log('element '+JSON.stringify(element[0]));
                        var name = element[i].name;
                        console.log('name '+name);    
                        var value = element[i].value;
                        if($A.util.isEmpty(value)){
                            value = '';    
                            
                        }
                        var attr = {};
                        attr[name] = value;
                        
                        console.log('attr '+JSON.stringify(attr));
                        itemWrapArr.push(attr);
                    }
                },this);
                
                var finalArr = {};   
                finalArr['recordtype'] = 'salesorder';
                finalArr['department'] = '19';
                console.log(nsCustomerId);
                finalArr['entity'] = nsCustomerId;
                finalArr['items'] = itemWrapArr;
                var data = JSON.stringify(finalArr);
                console.log('data '+data);
                
                console.log('itemWrapArr '+JSON.stringify(itemWrapArr));
                
                
                
                console.log('fidWrapArr '+JSON.stringify(fidWrapArr));
                
            }
            
            
        });

Apex code-(Only related code)

    @AuraEnabled
    Public static list<OrderItmWrap> createOrderInNs(String quoteId){
        list<OrderItmWrap> OrderItmWrapLst = new list<OrderItmWrap>();
        try{
            String nsCustomerId = '';
            String body = '';
            List<OrderItem> orderItmLst = new List<OrderItem>();
            nsCustomerId = [SELECT SBQQ__Account__r.Ns_Customer_ID__c FROM SBQQ__Quote__c where id=:quoteId][0].SBQQ__Account__r.Ns_Customer_ID__c;
            orderItmLst = [SELECT Item_Code__c,TotalPrice,Quantity,Description FROM OrderItem where Item_Code__c != '' and SBQQ__QuoteLine__r.SBQQ__Quote__c=:quoteId];
            //Getting Custom settings data
            List<Gong_Button_Field_Mappings__mdt> gbtnFm = [SELECT JSON_Field_Name__c,Field_Api_Name__c FROM Gong_Button_Field_Mappings__mdt];
            for(OrderItem ordrItm:orderItmLst)
            {
                sobject obj;
                list<Itemwrapper> itmwrapLst=new list<Itemwrapper>();
                for(Gong_Button_Field_Mappings__mdt gbtnFmRec:gbtnFm)
                {
                    Itemwrapper itmWap = new Itemwrapper();
                    itmWap.name=gbtnFmRec.JSON_Field_Name__c;
                    itmWap.value=String.valueOf(ordrItm.get(gbtnFmRec.Field_Api_Name__c));
                    itmwrapLst.add(itmWap);
                }
                OrderItmWrap ordWarp = new OrderItmWrap();
                ordWarp.ordId=ordrItm.Id;  
                ordWarp.customerId = nsCustomerId;
                ordWarp.itemWrapLst.addAll(itmwrapLst);
                OrderItmWrapLst.add(ordWarp);
            }
            system.debug('OrderItmWrapLst '+OrderItmWrapLst);            
            /*Http http = new Http();
HttpRequest request = new HttpRequest();
request.setEndPoint('callout:Netsuite_Salesforce_Integration'); //external URL
request.setBody(body);
request.setMethod('POST');
//request.setHeader('Authorization',header);
request.setHeader('Content-Type', 'application/json');
request.setTimeOut(120000);
HttpResponse response = http.send(request);
System.debug(response);
System.debug('response body '+response.getBody());*/
            
        }
        catch(Exception ex){
            system.debug('Exception at line: '+ex.getLineNumber()+' '+'The exception is '+ex.getMessage());
            
        }
        
        return OrderItmWrapLst;    
    }
    
    
    public class Itemwrapper{
        @AuraEnabled
        Public string name{get;set;}
        @AuraEnabled
        Public string value{get;set;}
    }   
    public class OrderItmWrap{
        @AuraEnabled
        Public string ordId{get;set;}
        @AuraEnabled
            Public list<Itemwrapper> itemWrapLst = new List<Itemwrapper>();
        @AuraEnabled Public string customerId{get;set;} 
       
    }
  

EDIT - Added entire Apex code.Here i am using custom metadata to store the variables.Items array i am storing in [SELECT JSON_Field_Name__c, Field_Api_Name__c FROM Gong_Button_Field_Mappings__mdt] query.

I was thinking to use Public string ordId to segregate the items. Please help!!.

  • I will suggest backtracking from Json to get Apex and then use the apex to get final json. You can convert your json to a apex class using online tools like json2apex and then use the generated class to populate the details. That class instance will give you exact same structure. – manjit5190 Jul 29 at 20:58
0

Rather than processing server response JSON in controller or handler I would recommend you to create the domain(wrapper) classes in Apex in the exact expected format and return that response from apex methods. Then your response.getReturnValues() will be automatically parsed in the same format and you will not need any additional processing in controllers/helpers.

I mean create the wrapper classes like below.

    public class OrderItem {
      @AuraEnabled
      public String item{get;set;}
      @AuraEnabled
      public String description{get;set;}
      @AuraEnabled
      public String quantity{get;set;}
      @AuraEnabled
      public String amount{get;set;}
      @AuraEnabled
      public String custcol_term{get;set;}
      @AuraEnabled
      public String custcol_total_price{get;set;}
    }

    public class orderWrap {
      @AuraEnabled
      public String recordtype{get;set;}
      @AuraEnabled
      public String department{get;set;}
      @AuraEnabled
      public String entity{get;set;}
      @AuraEnabled
      public String custbody_ava_shiptousecode{get;set;}
      @AuraEnabled
      public List<OrderItem> items {{get;set;}}
    }
| improve this answer | |
  • Thanks @SushantN for reply. I cannot make wrappers like that in Apex because i am storing the variables in custom metadata.And since it would be easy to make JSON in controller i send entire list of wrapper to js. – Deepak Agarwal Jul 30 at 3:46
  • I have created items in the form "name","value" to get the values in JS. – Deepak Agarwal Jul 30 at 4:02

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.