1

How to de-serialize following array of response from the url??I have to pass time stamp in the URL as follows:Tried Json to apex too but as it is post method can't use that.

String startdate= timestamp??
String Enddate = timestamp??

this I have to pass as post

http://getCustomers/startdate/20151101000001/enddate/20151130235959

[{"across_na_flag":0,"added_by_date":"\/Date(1231791151627-0500)\/","added_by_user_name":"sa","addr1":"American Products Inc","addr2":"PO Box 818","addr3":"Pineville, NC 28134-0818","addr4":"","addr5":"","addr6":"","addr_sort1":"ENDUSR","addr_sort2":"RETAIL","addr_sort3":"NONSNA","address_name":"American Products Inc","address_type":0,"affiliated_cust_code":"","aging_limit_bracket":3,"alt_location_code":"CHR","attention_email":"","attention_name":"Accounts Payable\/Cod","attention_phone":"7045882400","bal_fwd_flag":0,"check_aging_limit":1,"check_credit_limit":0,"check_display_comment":0,"check_extendedname_flag":0,"city":"Pineville","consolidated_invoices":0,"contact_email":"","contact_name":"","contact_phone":"7045882400","country":"US","country_code":"US","credit_limit":5000,"cust_po_allow_dup":0,"cust_po_req":0,"customer_code":"CS000890","date_opened":733440,"db_credit_rating":"","db_date":0,"db_num":"","ddid":null,"delivery_days":0,"dest_zone_code":"","dunn_message_code":"","dunning_group_id":"","entry_ordered_by":0,"extended_name":"","fin_chg_code":"N\/A","fob_code":"ORIGIN","forwarder_code":"","freight_code":"","freight_to_code":"","ftp":"AMEPROPI","guid":"P","inv_comment_code":"","invoice_copies":1,"iv_substitution":0,"late_chg_type":0,"limit_by_home":1,"location_code":"CHR","modified_by_date":"\/Date(1447995600000-0500)\/","modified_by_user_name":"598","nat_cur_code":"USD","note":"AMEPRO","one_cur_cust":1,"payer_soldto_rel_code":" ","payment_code":"CHK-3RD","phone_1":"7045882400","phone_2":"","postal_code":"28134-0818","posting_code":"3RDCHR","price_code":"CNGMHGR","price_level":"1","print_stmt_flag":0,"rate_type_home":"BUY","rate_type_oper":"BUY","remit_code":"LOCKBOX","resale_num":"718 6 060 39128","route_code":"","route_no":0,"salesperson_code":"","ship_complete_flag":0,"ship_to_code":"","ship_to_history":1,"ship_via_code":"BESTWAY","short_name":"American P","so_priority_code":"1","special_instr":"","state":"NC","status_type":1,"stmt_comment_code":"","stmt_cycle_code":"MNTHLYST","tax_code":"AVATAX","tax_exempt_cust_type":0,"tax_id_num":"","terms_code":"NET30","territory_code":"2055","timestamp":[0,0,0,0,156,175,77,153],"tlx_twx":"7045882559","trade_disc_percent":0,"url":"","valid_payer_flag":1,"valid_shipto_flag":1,"valid_soldto_flag":1,"vendor_code":"","writeoff_code":"OSCHR"}

This is what I was testing with but it is difficult with the following class?? I have to pass time stamp in the URL as post method how do I achieve this:

http://getCustomers/startdate/20151101000001/enddate/20151130235959.

After getting response I should de-serialize those as records batch wise so i wrote scheduler to invoke this class.

My question is to de-serialize the complex response as shown above and inserting as records and posting timestamp in the URl as post method.

How to use this class to insert and update records ??

public class Deserialise {

    public Integer across_na_flag;
    public String added_by_date;
    public String added_by_user_name;
    public String addr1;
    public String addr2;
    public String addr3;
    public String addr4;
    public String addr5;
    public String addr6;
    public String addr_sort1;
    public String addr_sort2;
    public String addr_sort3;
    public String address_name;
    public Integer address_type;
    public String affiliated_cust_code;
    public Integer aging_limit_bracket;
    public String alt_location_code;
    public String attention_email;
    public String attention_name;
    public String attention_phone;
    public Integer bal_fwd_flag;
    public Integer check_aging_limit;
    public Integer check_credit_limit;
    public Integer check_display_comment;
    public Integer check_extendedname_flag;
    public String city;
    public Integer consolidated_invoices;
    public String contact_email;
    public String contact_name;
    public String contact_phone;
    public String country;
    public String country_code;
    public Integer credit_limit;
    public Integer cust_po_allow_dup;
    public Integer cust_po_req;
    public String customer_code;
    public Integer date_opened;
    public String db_credit_rating;
    public Integer db_date;
    public String db_num;
    public Object ddid;
    public Integer delivery_days;
    public String dest_zone_code;
    public String dunn_message_code;
    public String dunning_group_id;
    public Integer entry_ordered_by;
    public String extended_name;
    public String fin_chg_code;
    public String fob_code;
    public String forwarder_code;
    public String freight_code;
    public String freight_to_code;
    public String ftp;
    public String guid;
    public String inv_comment_code;
    public Integer invoice_copies;
    public Integer iv_substitution;
    public Integer late_chg_type;
    public Integer limit_by_home;
    public String location_code;
    public String modified_by_date;
    public String modified_by_user_name;
    public String nat_cur_code;
    public String note;
    public Integer one_cur_cust;
    public String payer_soldto_rel_code;
    public String payment_code;
    public String phone_1;
    public String phone_2;
    public String postal_code;
    public String posting_code;
    public String price_code;
    public String price_level;
    public Integer print_stmt_flag;
    public String rate_type_home;
    public String rate_type_oper;
    public String remit_code;
    public String resale_num;
    public String route_code;
    public Integer route_no;
    public String salesperson_code;
    public Integer ship_complete_flag;
    public String ship_to_code;
    public Integer ship_to_history;
    public String ship_via_code;
    public String short_name;
    public String so_priority_code;
    public String special_instr;
    public String state;
    public Integer status_type;
    public String stmt_comment_code;
    public String stmt_cycle_code;
    public String tax_code;
    public Integer tax_exempt_cust_type;
    public String tax_id_num;
    public String terms_code;
    public String territory_code;
    public List<Integer> timestamp;
    public String tlx_twx;
    public Integer trade_disc_percent;
    public String url;
    public Integer valid_payer_flag;
    public Integer valid_shipto_flag;
    public Integer valid_soldto_flag;
    public String vendor_code;
    public String writeoff_code;

    global String jsonInput{get;set;}

    @future(callout=true) 
    public static void basicAuthCallout(){ 
    List<Lead> lst=new List<Lead>();   

    HttpRequest req = new HttpRequest();   
    req.setEndpoint('This is my endpoint URL');
    req.setMethod('Post');
    Http http = new Http();
    HTTPResponse res = http.send(req);

    String jsonInput=res.getBody();  
    process(jsonInput);
    private void process(string payload)   {  
    Map<String, Object> m =(Map<String,Object>)JSON.deserializeUntyped(payload);  
        //return (Deserialise) System.JSON.deserialize(json, Deserialise.class);
    }
    }
  • whats a issue with json to apex? thats works for me for your request... – kurunve Mar 25 '16 at 6:16
  • Thanks for response it works but how do I use that class to create records??For example I have deserialize the above class using json to apex for this URL docsample.herokuapp.com/jsonSample – Salesforce Learner Mar 25 '16 at 6:25
  • Then you just go via for loop for all records in array and create lead per invoice, exactly as you do in your code – kurunve Mar 25 '16 at 6:34
  • I have updated question – Salesforce Learner Mar 25 '16 at 8:43
  • How to call this class and insert records or do upsert. – Salesforce Learner Mar 25 '16 at 8:48
4

On the question of how to deserialize and insert this pattern should work:

@RestResource(urlMapping='/startdate/*')
global with sharing class YourClassName {

    // Cut and paste and edit class name from the JSON2Apex generated class
    public class Item {
        public Integer across_na_flag;
        public String added_by_date;
        ...
    }

    @HttpPost  
    global static void post() {
        String jsonString = RestContext.request.requestBody.toString();
        Item[] items = (Item[]) System.JSON.deserialize(jsonString, Item[].class);
        SObject[] sobs = new SObject[] {};
        for (Item item : items) {
            sobs.add(convert(item));
        }
        insert sobs;
    }

    private static AppropriateSObject__c convert(Item item) {
        // Add and call data type conversions methods as needed (e.g. dates)
        return new AppropriateSObject__c(
                across_na_flag__c = item.across_na_flag,
                added_by_date__c = toDate(item.added_by_date),
                ...
                );
    }

    private static Date toDate(String s) {
        ...
    }
}

PS

If the aim is to callout from Apex the code would look something like this:

public class YourClassName {

    // Cut and paste and edit class name from the JSON2Apex generated class
    public class Item {
        public Integer across_na_flag;
        public String added_by_date;
        ...
    }

    public void request(DateTime startDate, DateTime endDate) {
        String url = 'http://getCustomers'
                + '/startdate/'
                + toString(startDate)
                + '/enddate/'
                + toString(endDate)
                ;
        HttpRequest req = new HttpRequest();
        req.setEndpoint(url);
        req.setMethod(GET);
        HttpResponse res = new Http().send(req);
        if (res.getStatusCode() >= 200 && res.getStatusCode() < 300) {
            processResponse(res.getBody());
        } else {
            // Error handling
        }
    }

    private static void processResponse(Sting jsonString) {
        Item[] items = (Item[]) System.JSON.deserialize(jsonString, Item[].class);
        SObject[] sobs = new SObject[] {};
        for (Item item : items) {
            sobs.add(convert(item));
        }
        insert sobs;
    }

    private static AppropriateSObject__c convert(Item item) {
        // Add and call data type conversions methods as needed (e.g. dates)
        return new AppropriateSObject__c(
                across_na_flag__c = item.across_na_flag,
                added_by_date__c = toDate(item.added_by_date),
                ...
                );
    }

    private static Date toDate(String s) {
        ...
    }

    private static String toString(DateDime dt) {
        // Format string docmentation:
        // https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
        return dt.format('yyyyMMddhhmmssSSS');
    }
}
  • Thanks for reply keith..I have updated class in question...this what I am looking at..Invoking endpoint URL and get json response and derialize array and create records.. – Salesforce Learner Mar 25 '16 at 9:41
  • @SalesforceLearner I've added a second piece of code. – Keith C Mar 25 '16 at 10:00
  • Thanks it helped ! Awesome answer ....As you can see my url has parameters like start date and end date...this should be passed as time stamp how do i store timestamp in Startdate and Enddate string based on that I am fetching info.....I have updated my string and should be done as post – Salesforce Learner Mar 25 '16 at 11:24
  • @SalesforceLearner I added ode to change DateTime objects into part of the URL. – Keith C Mar 25 '16 at 11:38
  • Thanks Keith C great help.... can I have email id? – Salesforce Learner Mar 29 '16 at 8:34

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.