How to remove attributes before JSON is sent from Custom REST Apex?

I get back JSON like the following:

         Id = a0Ef0000002TPKVEA4;
         Name = a0Ef0000002TPKV;
         attributes =             {
             type = "Market__c";
             url = "/services/data/v29.0/sobjects/Market__c/a0Ef0000002TPKVEA4";

The attributes portion doubles the data size. I’ve searched the docs but can’t find a way to remove it. Here is the code I am using

 global static Aggregate doGet() {
     RestRequest req = RestContext.request;
     string userid = req.params.get('UserId');

     try {
         User user = [SELECT FirstName, LastName, Title, Email, Phone, MobilePhone,
          Street, City, State, PostalCode, Country, LevelOfCare__c, Username, PERNER__c
          FROM User WHERE Id = :userid];

          List<Market__c> markets = [SELECT Id, Name FROM Market__c];

         return new Aggregate(user, markets);         
     catch (exception e) {
         return null;

 global class Aggregate {
     public User user {get; set;}
     public List<Market__c> markets {get; set;}

     public Aggregate(User u, List<Market__c> m) {
         user = u;
         markets = m;
 } }


As it is custom Apex code, instead of directly returning the SObject, return a simple “bean” class that just has an Id and Name property with the values copied from the SObject:

public class Bean {
    public Id Id;
    public String Name;
    Bean(SObject sob) {
       this.Id = sob.Id;
       this.Name = (String) sob.get('Name');


Based on the posted code, it is the nested SObjects that you need to eliminate:

global class Aggregate {

    public Bean user {get; set;}
    public List<Bean> markets {get; set;}

    public Aggregate(User u, List<Market__c> ms) {
        user = new Bean(u);
        markets = new List<Bean>();
        for (Market__c m : ms) {
            markets.add(new Bean(m));

Source : Link , Question Author : Bradley Thomas , Answer Author : Keith C

Leave a Comment