Friday, July 31, 2015

Status=Length Required, StatusCode=411 error in Apex callout

HttpRequest request = new HttpRequest();request.setHeader('Content-Length', '512'); 

Generate Json Data



Here is Simple classs to form json data..

public class ParentRecord {
    public String recordType, entity, job;
    public ChildRecord[] item;
    public ParentRecord(String recordType, String entity, String job) {
        this.recordType = recordType;
        this.entity = entity;
        this.job = job;
        item = new ChildRecord[0];
    }
}

public class ChildRecord {
    public String item;
    public Decimal quantity, amount;
    public ChildRecord(String item, Decimal quantity, Decimal amount) {
        this.item = item;
        this.quantity = quantity;
        this.amount = amount;
    }
}


pass paramenters to the above class using below code.



// Query parent and children, you can do both at once.
// Replace object names, relationship names, and field names.
Parent record = [SELECT Id, recordType, entity, job, (SELECT Id, Item, quantity, amount FROM Children) FROM Parent WHERE Id = :someId];

// Create a parent record entry from the utility class
ParentRecord parent = new ParentRecord(record.recordType, record.Entity, record.job);
// Loop through and build the item list
for(Child lineItem: record.Children) {
    parent.item.add(new ChildRecord(lineItem.Item, lineItem.quantity, lineItem.Amount));
}



Now convert the data into json using JSON.serialize() method
String jsondatagen= JSON.serialize(parent);