• divya manohar
  • NEWBIE
  • 70 Points
  • Member since 2015

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 14
    Questions
  • 19
    Replies
Hi, 
I am trying to understand the basics of OAUTH 2.0 using username & password format.
I have 2 instances of sandbox api say user1 and user2 and both have system admin profile.
I have developed a rest api in user 1(say source) and I want to access the same in user2(say destination) by provding client ID,client secret,username and password.

Here is what I have done so far.

a) In user1(source) I have a rest api

b) In user2(destination), I have created connected app, enabled OAuth, provided the callback url as "https://ap2.salesforce.com/apex/RestApiResponse".

RestApiResponse is a visualforce page created in user2(destination)

c) In user2 in remote site settings, I have registered the url   https://login.salesforce.com/services/oauth/token

d) In user2 I have created apex controller and visual force page, the code is shown below
 
public class restExample1
{
  public String ClientSecret{get;set;}
  public String ClientID{get;set;}
  public String UserName{get;set;}
  public String Password{get;set;}
  public String Result{get;set;}
  public String accessToken{get;set;}
  
  public PageReference GetAccessToken()
  {
    HttpRequest request=new HttpRequest();
    
    request.setEndPoint('https://login.salesforce.com/services/oauth/token');
    
    request.setMethod('POST');
    
    String reqbody = 'grant_type=password&client_id='+clientId+'&client_secret='+clientSecret+'&username='+username+'&password='+password;
    
    request.setBody(reqbody);
    
    Http p=new Http();
    
    HttpResponse response=p.send(request);
    
    result=response.getBody();
    
    system.debug('@@@result = '+result);
    
    return null;
 }
}

visual force page : RestApiResponse
<apex:page controller="restExample1">
<apex:form>
  <apex:pageBlock title="RestApiExample">
  
       <apex:pageBlockSection title="OAuth2.0 username & Password"
                              collapsible="false">
                              
       
       <apex:pageBlockSectionItem >
            <apex:outputLabel value="ClientID"/>
            
            <apex:inputText value="{!ClientID}"/>
            
       </apex:pageBlockSectionItem>
       
       <apex:pageBlockSectionItem >
            <apex:outputLabel value="ClientSecret"/>
            
            <apex:inputText value="{!ClientSecret}"/>
            
       </apex:pageBlockSectionItem>
       
           
       <apex:pageBlockSectionItem >
            <apex:outputLabel value="UserName"/>
            
            <apex:inputText value="{!UserName}"/>
            
       </apex:pageBlockSectionItem>
       
       <apex:pageBlockSectionItem >
            <apex:outputLabel value="Password"/>
            
            <apex:inputText value="{!Password}"/>
            
       </apex:pageBlockSectionItem>


       </apex:pageBlockSection>
  
       <apex:pageBlockButtons >
       
         <apex:commandButton value="Get Access Token"
                             action="{!GetAccessToken}"
                             reRender="token"/>
       
       </apex:pageBlockButtons>
  </apex:pageBlock>
  
  <apex:pageBlock title="Access Token"
                  id="token">
  

     {!accesstoken}
        
   </apex:pageBlock>

</apex:form>

</apex:page>

when the vf pages executes and I click the command button, I see that the debug logs contains some HTML format and not the much required JSON string. , so I am unable to generate the accesstoken.

I am stuck here and please correct me if I am missing any step

Thanks
divya



 
{ "rb": { "a": {
			"Name": "LG1",
			"SLAExpirationDate__c": "2016-4-21",
			"Active__c": "Yes",
			"SLA__c": "Platinum",
			"SLASerialNumber__c": "200"
		},
		"cList": [{
			"FirstName": "K1",
			"LastName": "K2"
		}, {
			"FirstName": "K3",
			"LastName": "K4"
		}]
	},
	{
			"Name": "LG2",
			"SLAExpirationDate__c": "2016-4-21",
			"Active__c": "Yes",
			"SLA__c": "Platinum",
			"SLASerialNumber__c": "200"
		},
		"cList": [{
			"FirstName": "K5",
			"LastName": "K6"
		},
                {
			"FirstName": "K7",
			"LastName": "K8"
		}]
	
}
Hello 
I am getting an error in above json file.
for multiple accounts I have multiple contacts.

divya
 
Hello
I have created a rest resource which will insert a single account record and can insert multiple contact records.
@RestResource(urlMapping='/BulkInsertaccountcontact/*')
global class Bulkinsert_accountcontact
{
   global class RequestBody 
   {
       Account a; //create single account
       List<Contact> cList;
   }
   
   global class myWrapper
   {
      Account a;
      List<Contact> cList;
      public string status;
      public string message;
   }
   
   @HttpPost
   global static myWrapper doPost(RequestBody rb)
   {
      RestRequest req=RestContext.request;
      RestResponse res=RestContext.response;
   
      myWrapper response=new myWrapper(); //this is object of wrapper class
      
      try
      {
        Insert rb.a;
        
        response.a=rb.a;
        
        for(Contact con:rb.cList)
        {
           con.AccountID=rb.a.ID;
        }
        
        //we need to insert contact List also
        Insert rb.cList;
        response.cList=rb.cList;
        response.status='Success';
        response.message='Created Successfully';
        
      }
      catch(exception ex)
      {
         response.a=null;
         response.cList=null;
         response.status='ERROR';
         response.Message='could not create record'+ ex.getMessage();
      }
      
      return response;
   }
}

Its working fine a but my requirement is to to create multiple account records in JSON body and each account can more than 1 contact records.

I am using workbench to test the rest resource.

I think I need to make a change as follows.
 global class RequestBody 
   {
       List<Account> a; 
       List<Contact> cList;
   }
   
   global class myWrapper
   {
      List<Account> a;
      List<Contact> cList;
      public string status;
      public string message;
   }

Please let me know how I can proceed further.

divya
RestResource(urlMapping='/myrest2/*')
global with sharing class Rest_Class2
{
   //method will take ID from URL and display the details

   @HTTPGet
   global static Account[] doGet()
   {
        RestRequest req = RestContext.request;

        RestResponse res = RestContext.response;

        String currentindustry=req.requestURI.substring(req.requestURI.lastIndexof('/')+1;

        Account[] acts = new Account[]{};

        if (currentIndustry=='all')

           acts=[select name,type,industry,phone  from Account];
        else
        Account[] acts= select Name from Account where Industry=:currentindustry];

        return acts;
   }
}

Hello

Please let me know how to write a test class for the above and achieve 100%

Thanks
divya
@RestResource(urlMapping='/myrest2/*')
global with sharing class Rest_Class2
{
   @HTTPGet
   global static Account[] doGet()
   {
      RestRequest req = RestContext.request;

      RestResponse res = RestContext.response;
      
      String currentIndustry=req.requestURI.substring(req.requestURI.lastIndexof('/')+1);
      
      Account[] acts=new Account[]{};
      
      if (currentIndustry=='all')
      
         acts=[select Name,Industry from account where Industry=:currentIndustry];
      
      else
      
          acts=[select Name from account where Industry=:currentIndustry];
         
      return acts;
   } 
   
}
Hi friends

I have written a rest resource where I want to display all account where Industry='Energy'. when I test this is work bench it is showing error as 
Service not found at: /services/apexrest/industry/enerygy

If it do as       /services/apexrest/industry/all    then it will show all accounts
But either way its not showing records.
Pls guide me.

divya
 
Hello
I am validating my salesforce concepts.
when vf page loads it will generate 4 records where I can enter values . when I click Getrows button I am able to fetch all data.
now out of 4 records if I select 4 th record for delete then the first record gets deleted not the fourth one.
Please let me know the issue
public class Student_Wrapper
{
    public String name      {set;get;}
    public String course    {set;get;}
    public String branch    {set;get;}
    public Decimal fee      {set;get;}
    public Boolean flag     {set;get;}
}

public class StudentLineItems
{

  public Integer rowNo { get; set; }
  
  public List<Student_Wrapper> students{get;set;}
  
  public List<Student_Wrapper> selected{get;set;}
  
  public StudentLineItems()
  {
    students=new List<Student_Wrapper>();
    addRows();
  }
  
  public void addRows()
  {
    students=new List<Student_Wrapper>();
    
    for(integer i=1;i<=4;i++)
    {
       Student_Wrapper sd=new Student_Wrapper();
       students.add(sd);
    }
  }
  
  public void getData()
  {
        if (students != NULL)
        {
          selected=new List<Student_Wrapper>();
        
          for(Student_Wrapper sw:students)
          {
            if(sw.flag == true)
                 selected.add(sw);
          }
        }
  }
  
  public void addEle()
  {
       Student_Wrapper s=students.get(rowNo);
              
        if(rowNo+1<students.size())
        
            students.add(rowNo+1,s); 
            
        else
        
            students.add(s);
  }
  
  public void removeEle() 
  {   
   if (rowNo <=students.size())
      students.remove(rowNo);
  }
}

<apex:page controller="StudentLineItems">

<apex:form id="frm1">

<apex:inputHidden value="{!rowNo}" 
                  id="hid" />

  <apex:pageBlock title="student details"
                  id="pb1">
                  
  <apex:pageBlockButtons location="top">
  
  <apex:commandButton value="Add Rows"
                      action="{!addRows}"/>  
                         
  <apex:commandButton value="Get Rows"
                      action="{!getData}"/>                
  
  </apex:pageBlockButtons>
                  
    <apex:pageBlockTable value="{!students}"
                         var="stud"
                         id="pgblck1">
                     
     <apex:column >
     
     <apex:inputCheckbox value="{!stud.flag}"/>
     
     </apex:column>
     
     <apex:column headerValue="Name">
     <apex:inputText value="{!stud.Name}" />
     </apex:column>
                       
     <apex:column headerValue="course">
     <apex:inputText value="{!stud.course}" />
     </apex:column>
                  
     <apex:column headerValue="branch">
     
     <apex:inputText value="{!stud.branch}"/>
     </apex:column>
     
     <apex:column headerValue="fee">
     
     <apex:inputText value="{!stud.fee}"/>
     </apex:column>
         
     <apex:column >
          
                   <apex:commandButton value="Add"
                                       id="b1" 
                                       action="{!addEle}"/>
                                                                              
                   <apex:commandButton value="Del"
                                       id="b2" 
                                       action="{!removeEle}" />
               </apex:column>
    </apex:pageBlockTable>
     
  </apex:pageBlock>
    
<apex:pageBlock title="Student data">
                
   <apex:pageBlockTable value="{!selected}" 
                        var="a">
                
      <apex:column headerValue="Student Name">
      
                    <apex:outputText value="{!a.name}" />
      </apex:column>
      
      <apex:column headerValue="Course">
      
             <apex:outputText value="{!a.course}"/>
             
       </apex:column>
       
       <apex:column headerValue="Branch">
       
             <apex:outputText value="{!a.branch}"/>
             
        </apex:column>
        
        <apex:column headerValue="Fee">
        
          <apex:outputText value="{!a.fee}"/>
          
         </apex:column>   
</apex:pageBlockTable>          
</apex:pageBlock>

        
</apex:form>
</apex:page>

 
Hello
Pls explain what is dynamic visual force bindings?
How to implement in salesforce and in how to use in project?

divya
Hello
I have a requirement wherein I need to have a custom button (Fetch records) in Account object List View, which will show only Name,Phone and Industry=consulting.

My vf page is working and I have added the button to list view and when I select AllAcounts it shows the vf page with records.
But I need only those records where Industry=consulting and here I am getting all the records.
Is my approach right ? pls guide me
public class AccountExt
{
    //List<Account> acctList{get;set;}
    public AccountExt(ApexPages.StandardSetController controller) { }
    
    public List<Account> accountrec()
    {
       List<Account> acctList=[select Name,Phone,Industry from Account where Industry='Consulting'];

       ApexPages.StandardSetController ssc=new ApexPages.StandardSetController(acctList); //Instatiate standardsetcontroller

       return ssc.getRecords(); //getRecords method of StandardSetController
    }
}

<apex:page standardController="Account"
           extensions="AccountExt"
           recordSetVar="Accounts"
           tabStyle="Account"
           sidebar="false">
          
<apex:pageBlock title="Account">

 <apex:pageBlockTable value="{!Accounts}"
                     var="a">
 
 <apex:column value="{!a.Name}" 
              headerValue="Name"/>
              
 <apex:column value="{!a.Phone}" 
              headerValue="Phone"/>
              
 <apex:column value="{!a.Industry}" 
              headerValue="Industry"/>
 </apex:pageBlockTable>
 </apex:pageBlock>
</apex:page>
divya
 
Hello
I have created visual force page to navigate the account list view.
when I execute I get error"attempt to deference a null object"
pls le tme know eeher I am going wrong.
public class ListViewDemo
{

   string basequery='Select ID, Name FROM Account ORDER BY NAME ASC';
  
   private Integer pageSize = 10;
   
   public String AccFilterId {get; set;}

   public ListViewDemo(){}


   public ApexPages.StandardSetController AccSetController  //this is a property
   {
     get
        {
          if (AccSetController == null)
          {
            ApexPages.StandardSetController AccSetController=new ApexPages.StandardSetController(Database.getQueryLocator(basequery));
     
            AccSetController.setPageSize(pageSize);

            if (AccFilterId != null)
            {
              AccSetController.setFilterID(AccFilterId);
            }
          }
           
          return AccSetController;
        }
     set;
   }
   
   public ListViewDemo(ApexPages.StandardSetController c) {   }


   //Navigate to first Page
    public void firstPage()
    {
      AccSetController.first();

    }

    //Navigate to last Page
    public void lastPage()
    {
      AccSetController.last();
    }


    //Navigate to Next page

    public void next()
    {
      if(AccSetController.getHasNext())
      {
        AccSetController.next();
      }
    }


    //Navigate to Prev Page
    public void prev()
    {
      if(AccSetController.getHasPrevious())
      {
        AccSetController.previous();
      }
    }
    
    public SelectOption[] getAccountExistingViews()
    {
     return AccSetController.getListViewOptions();
    }
    
    
    public List<Account> getAccounts()
    {
        return AccSetController.getRecords();
    }

    
    public PageReference resetFilter()
    {
        AccSetController = null;
        
        AccSetController.setPageNumber(1);
        
        return null;
    }
}

<apex:page controller="ListViewDemo">
  
  <apex:form id="pageForm">
  
  <apex:selectList value="{!AccFilterId}"
                   size="1"
                   id="filterMenu">
                   
  <apex:selectOptions value="{!AccountExistingViews}"/>
  <apex:actionSupport event="onchange"  
                      action="{!resetFilter}" 
                      rerender="AccntTable" 
                      status="ajaxStatus"/>
  </apex:selectList>
  
  <apex:actionStatus id="ajaxStatus" 
                     startText="Loading..."  
                     stopText=""/>
  
   <apex:pageBlock title="Accounts">
   
    <apex:pageBlockButtons>

                <apex:commandButton action="{!firstPage}" 
                                    value="|<<" reRender="AccntTable"  
                                    status="ajaxStatus"/>

                <apex:commandButton action="{!prev}" 
                                    value="<" reRender="AccntTable"  
                                    status="ajaxStatus" />

                <apex:commandButton action="{!next}" value=">"
                                    reRender="AccntTable" 
                                    status="ajaxStatus" />

                <apex:commandButton action="{!lastPage}" 
                                    value=">>|"
                                    reRender="AccntTable"  
                                    status="ajaxStatus" />

            </apex:pageBlockButtons>

    <apex:pageBlockTable value="{!Accounts}" 
                         var="item" id="AccntTable">

                        <apex:column value="{!item.ID}"/>
                        <apex:column value="{!item.Name}"/>
                        <apex:column value="{!item.Phone}"/>

            </apex:pageBlockTable>

   
   </apex:pageBlock>
  
  </apex:form>
  
</apex:page>

 
Hi
New to salesforce and looking to consolidate concepts.
when I select city name picklist the places picklist displays the values but it doesnt display the default value.
I want to display the default value in place picklist when I select the a city name from city picklist.
public class PickListExample4 
{
  public Map<String,List<String>> cityMap{get;set;}
  
  public List<SelectOption> cities{get;set;}
  public List<SelectOption> places{get;set;}
  
  public string selected{get;set;}

  public Pagereference Display()
  {
     cityMap=new Map<String,List<String>>();
     cities=new List<SelectOption>();
     places=new List<SelectOption>();
     
     List<String>  hydplaces=new List<String>{'SRNagar','LBNagar'};
     List<String>  banglplaces=new List<String>{'Electronics City','Malleswaram'};
     
     cityMap.put('Hyderabad',hydplaces);
     cityMap.put('Bangalore',banglplaces);
          
     SelectOption n=new SelectOption('none','--None--');
     cities.add(n);
     places.add(n);

     Set<string> keys=cityMap.Keyset();
    
     for(String s:keys)
     {
            SelectOption op1=new SelectOption(s,s);
            cities.add(op1); //Bind cities to picklist.
     }
     return null;
  }
    
  public void getData()
  {
    if (selected != 'none')
    {
       places.clear();
       
       //create places picklist
       SelectOption n=new SelectOption('none','--None--');
       places.add(n);
       
       List<String> myplaces=cityMap.get(selected);
       system.debug('==>myplaces'+myplaces); //this will fetch the places for the selected city
       
       //Now bind the places to picklist
       for(string s:myplaces)
       {
          SelectOption op=new SelectOption(s,s);
          places.add(op); //Bind cities to picklist.
       }
    }
  }
}
<apex:page controller="PickListExample4"
           action="{!Display}">

<apex:form >
<apex:pageBlock title="Field dependency">

<apex:pageBlockSection >

<apex:pageBlockSectionItem >
   <apex:outputLabel value="Cities"/>
   <apex:selectList size="1" 
                     value="{!selected}">
                  
  <apex:selectOptions value="{!cities}"/>
  <apex:actionSupport event="onchange"
                      reRender="one"
                      action="{!getData}"/>

</apex:selectList>
</apex:pageBlockSectionItem>

<apex:pageBlocksectionItem>
                    <apex:outputLabel value="Places"/>
                    <apex:selectList  size="1" 
                                      id="one">
                    <apex:selectOptions value="{!places}" />
                    </apex:selectList>
 </apex:pageBlocksectionItem>
</apex:pageBlockSection>
</apex:pageBlock>
</apex:form>
</apex:page>
divya manohar
Hello 

I am deserialize json input but face error as follows.

I am facing an error as:Unknown field: My_Invoice_list.InvoiceWrapper.invoiceList
Error is in expression '{!deserialize}' in component <apex:commandButton> in page vf_invoicelist: (System Code)
Class.My_Invoice_list.deserialize: line 39, column 1
An unexpected error has occurred. Your solution provider has been notified. (System)

Below is the apex class code and vf page code.
 
public class My_Invoice_list
{
   public class InvoiceList 
   {
        public Double totalPrice {get;set;} 
        public String statementDate {get;set;} 
        public List<LineItems> lineItems {get;set;} 
        public Integer invoiceNumber {get;set;} 
   }
   
   public class LineItems
   {
      public Double UnitPrice {get;set;} 
      public Double Quantity {get;set;} 
      public String ProductName {get;set;} 
   }
  
   public class InvoiceWrapper
   {
      public list<InvoiceList> invoice_wrapper{get;set;}
   }
   
   public InvoiceWrapper invoice{get;set;}
   
   public void deserialize()
   {
   
     Http p = new Http();
     
     HttpRequest request = new HttpRequest();
     
     request.setEndPoint('https://docsample.herokuapp.com/jsonSample');
     
     request.setHeader('Content-type', 'application/json');      
     
     request.setMethod('GET');
     
     HttpResponse response=p.send(request);
     invoice=(InvoiceWrapper)JSON.deserializeStrict(response.getBody(),InvoiceWrapper.class);
          
   }
}
 
<apex:page controller="My_Invoice_list">
<apex:form >

<apex:pageBlock title="Deserialize JSON Resposne">

<apex:pageBlockSection>
<apex:pageBlockSectionItem>

<apex:commandButton value="submit"
                    action="{!deserialize}"
                    reRender="invoicetable"/>
                    
</apex:pageBlockSectionItem>
</apex:pageBlockSection>
</apex:pageBlock>            

<apex:pageBlock>
<apex:pageBlockTable value="{!invoice.invoice_wrapper}"
                     var="inv"
                     id="invoicetable">

                      <apex:column value="{!inv.totalPrice}" headerValue="TotalPrice" />
                      <apex:column value="{!inv.statementDate}" headerValue="statementDate" />
                     
</apex:pageBlockTable>
</apex:pageBlock>   
</apex:form>
</apex:page>

I am not understanding how to display the line items. 

divya
 
Hi
I am trying to understand basics of displaying data in visual force page.
Below is the code:
public class HttpExample3
{
   public string result{get;set;}
   public Double grand_total{get;set;}
   public InvoiceList inv{get;set;}
   
   public string callservice()
   {
     Http p = new Http();
     
     HttpRequest request = new HttpRequest();
     
     request.setEndPoint('https://docsample.herokuapp.com/jsonSample');
     
     request.setHeader('Content-type', 'application/json');      
     
     request.setMethod('GET');
     
     HttpResponse response=p.send(request);
     
     return response.getBody();
               
    }
    
    public void GetTotalPrice()
    {
      grand_total=InvoiceList.TotalPrice(callservice());
    }
 }

<apex:page controller="HttpExample3">
<apex:form>
<apex:pageBlock title="GetResponse">

<apex:pageblockSection>

<apex:pageblockSectionItem>
<apex:commandButton value="GetResponse"
                      action="{!callservice}"/>


</apex:pageblockSectionItem>
</apex:pageblockSection>

</apex:pageBlock>

<apex:pageBlock title="TotalPrice"> 

<apex:pageblockSection>

<apex:pageblockSectionItem>
<apex:commandButton value="GetTotalPrice"
                      action="{!GetTotalPrice}"/>

 </apex:pageblockSectionItem>

</apex:pageblockSection>
 {!grand_total}
</apex:pageBlock>

</apex:form>

</apex:page>

public class InvoiceList
{
        public static Double totalPrice{get;set;} 
        public DateTime statementDate {get;set;} 
        public List<LineItems> lineItems {get;set;} 
        public Integer invoiceNumber {get;set;} 
        public static double grand_total=0.0; 
                       
        public static double TotalPrice(string jsonString)
        {
          System.JSONParser jp=JSON.createParser(jsonString);
          
          while (jp.nextToken() != Null)
          {
             if ((jp.getCurrentToken() == JSONToken.FIELD_NAME) && jp.getText() == 'totalPrice')
             {
               jp.nextToken();
               grand_total+=jp.getDoubleValue();     
             }
          }
          
         return grand_total;
       }

       public class LineItems
       {
        public Double UnitPrice {get;set;} 
        public Double Quantity {get;set;} 
        public String ProductName {get;set;} 
       }
 }

I am making callservice method have return type because I need the response in other calculations.
code works fine when I click Get Total price button , but it fails when I click callservice button.
I get error as : he name can only contain underscores and alphanumeric characters. It must begin with a letter and be unique, and must not include spaces, end with an underscore, or contain two consecutive underscores. "

Please help me .

divya

 
friends
I have a json file , I want to use deserializeuntyped method to understand it.

public class Jsonexample5
{
   public string result{get;set;}
   
   public Jsonexample5()
   {
     string jsonInput='{"response":{"count":1,"benchmark":0.22567009925842,"requests":[{"request":{"id":537481,"image_thumbnail":"","title":"Request for new bin(s) - residential","description":"Propmain ref  3234-1114","status":"submitted","address":"36 Pine Tree Close","location":"Peterborough, England","zipcode":"PE1 1EJ","user":"","date_created":1417173208,"count_comments":0,"count_followers":0,"count_supporters":0,"lat":52.599967,"lon":-0.233482,"user_follows":0,"user_comments":0,"user_request":1,"rank":"0"}}],"status":{"type":"success","message":"Success","code":200,"code_message":"Ok"}}}';
       
     Map<String,Object> jsmap = (Map<String,Object>)JSON.deserializeUntyped(jsonInput);
     system.debug('==>'+jsmap);
 
   }
}

I have 2 things to clarify
a) when I execute the above in developer console I get the deserialized format but it does not include attributes after location.
    i.e atrributes like zipcode , user , date_created , count_comments  etc are missing.

    The same input json string when executed in    http://codebeautify.org/jsonviewer#  gives all the attributes.

    I want to know why is this happening. Am I missing something:?


b) In real time scenario , do we use third pary tools to generate classes for json input or we have to manually write our own wrapper classes?

thanks
divya manohar
 
Hello
This is my first post.

I have a json string which I want to deserialize and get the values.

public class CompanyContactsWrapper
{
     public string contact{get;set;}
     public string postalcode{get;set;}
     public string contactnumber{get;set;}
}

public class Jsonexample4
{
   public CompanyContactsWrapper CompanyContacts{get;set;}
   
   public Jsonexample4()
   {
    
     string jsonInput='{"CompanyContacts":[{"contact":"pn0","postalcode":"0","contactnumber":"pc0"},{"contact":"pn1","postalcode":"1","contactnumber":"pc1"},{"contact":"pn2","postalcode":"2","contactnumber":"pc2"}]}';
          
          
     CompanyContacts= (CompanyContactsWrapper)JSON.deserialize(jsonInput,CompanyContactsWrapper.class);
         
     system.debug('==>'+CompanyContacts);
   
   }
}

In developer console I create an object and execute.
I get contact=null, postalcode=null & contactnumber=null.

pls tell where I have gone wrong?

thanks
divya manohar
{ "rb": { "a": {
			"Name": "LG1",
			"SLAExpirationDate__c": "2016-4-21",
			"Active__c": "Yes",
			"SLA__c": "Platinum",
			"SLASerialNumber__c": "200"
		},
		"cList": [{
			"FirstName": "K1",
			"LastName": "K2"
		}, {
			"FirstName": "K3",
			"LastName": "K4"
		}]
	},
	{
			"Name": "LG2",
			"SLAExpirationDate__c": "2016-4-21",
			"Active__c": "Yes",
			"SLA__c": "Platinum",
			"SLASerialNumber__c": "200"
		},
		"cList": [{
			"FirstName": "K5",
			"LastName": "K6"
		},
                {
			"FirstName": "K7",
			"LastName": "K8"
		}]
	
}
Hello 
I am getting an error in above json file.
for multiple accounts I have multiple contacts.

divya
 
@RestResource(urlMapping='/myrest2/*')
global with sharing class Rest_Class2
{
   @HTTPGet
   global static Account[] doGet()
   {
      RestRequest req = RestContext.request;

      RestResponse res = RestContext.response;
      
      String currentIndustry=req.requestURI.substring(req.requestURI.lastIndexof('/')+1);
      
      Account[] acts=new Account[]{};
      
      if (currentIndustry=='all')
      
         acts=[select Name,Industry from account where Industry=:currentIndustry];
      
      else
      
          acts=[select Name from account where Industry=:currentIndustry];
         
      return acts;
   } 
   
}
Hi friends

I have written a rest resource where I want to display all account where Industry='Energy'. when I test this is work bench it is showing error as 
Service not found at: /services/apexrest/industry/enerygy

If it do as       /services/apexrest/industry/all    then it will show all accounts
But either way its not showing records.
Pls guide me.

divya
 
Hello
I have a requirement wherein I need to have a custom button (Fetch records) in Account object List View, which will show only Name,Phone and Industry=consulting.

My vf page is working and I have added the button to list view and when I select AllAcounts it shows the vf page with records.
But I need only those records where Industry=consulting and here I am getting all the records.
Is my approach right ? pls guide me
public class AccountExt
{
    //List<Account> acctList{get;set;}
    public AccountExt(ApexPages.StandardSetController controller) { }
    
    public List<Account> accountrec()
    {
       List<Account> acctList=[select Name,Phone,Industry from Account where Industry='Consulting'];

       ApexPages.StandardSetController ssc=new ApexPages.StandardSetController(acctList); //Instatiate standardsetcontroller

       return ssc.getRecords(); //getRecords method of StandardSetController
    }
}

<apex:page standardController="Account"
           extensions="AccountExt"
           recordSetVar="Accounts"
           tabStyle="Account"
           sidebar="false">
          
<apex:pageBlock title="Account">

 <apex:pageBlockTable value="{!Accounts}"
                     var="a">
 
 <apex:column value="{!a.Name}" 
              headerValue="Name"/>
              
 <apex:column value="{!a.Phone}" 
              headerValue="Phone"/>
              
 <apex:column value="{!a.Industry}" 
              headerValue="Industry"/>
 </apex:pageBlockTable>
 </apex:pageBlock>
</apex:page>
divya
 
Hello
I have created visual force page to navigate the account list view.
when I execute I get error"attempt to deference a null object"
pls le tme know eeher I am going wrong.
public class ListViewDemo
{

   string basequery='Select ID, Name FROM Account ORDER BY NAME ASC';
  
   private Integer pageSize = 10;
   
   public String AccFilterId {get; set;}

   public ListViewDemo(){}


   public ApexPages.StandardSetController AccSetController  //this is a property
   {
     get
        {
          if (AccSetController == null)
          {
            ApexPages.StandardSetController AccSetController=new ApexPages.StandardSetController(Database.getQueryLocator(basequery));
     
            AccSetController.setPageSize(pageSize);

            if (AccFilterId != null)
            {
              AccSetController.setFilterID(AccFilterId);
            }
          }
           
          return AccSetController;
        }
     set;
   }
   
   public ListViewDemo(ApexPages.StandardSetController c) {   }


   //Navigate to first Page
    public void firstPage()
    {
      AccSetController.first();

    }

    //Navigate to last Page
    public void lastPage()
    {
      AccSetController.last();
    }


    //Navigate to Next page

    public void next()
    {
      if(AccSetController.getHasNext())
      {
        AccSetController.next();
      }
    }


    //Navigate to Prev Page
    public void prev()
    {
      if(AccSetController.getHasPrevious())
      {
        AccSetController.previous();
      }
    }
    
    public SelectOption[] getAccountExistingViews()
    {
     return AccSetController.getListViewOptions();
    }
    
    
    public List<Account> getAccounts()
    {
        return AccSetController.getRecords();
    }

    
    public PageReference resetFilter()
    {
        AccSetController = null;
        
        AccSetController.setPageNumber(1);
        
        return null;
    }
}

<apex:page controller="ListViewDemo">
  
  <apex:form id="pageForm">
  
  <apex:selectList value="{!AccFilterId}"
                   size="1"
                   id="filterMenu">
                   
  <apex:selectOptions value="{!AccountExistingViews}"/>
  <apex:actionSupport event="onchange"  
                      action="{!resetFilter}" 
                      rerender="AccntTable" 
                      status="ajaxStatus"/>
  </apex:selectList>
  
  <apex:actionStatus id="ajaxStatus" 
                     startText="Loading..."  
                     stopText=""/>
  
   <apex:pageBlock title="Accounts">
   
    <apex:pageBlockButtons>

                <apex:commandButton action="{!firstPage}" 
                                    value="|<<" reRender="AccntTable"  
                                    status="ajaxStatus"/>

                <apex:commandButton action="{!prev}" 
                                    value="<" reRender="AccntTable"  
                                    status="ajaxStatus" />

                <apex:commandButton action="{!next}" value=">"
                                    reRender="AccntTable" 
                                    status="ajaxStatus" />

                <apex:commandButton action="{!lastPage}" 
                                    value=">>|"
                                    reRender="AccntTable"  
                                    status="ajaxStatus" />

            </apex:pageBlockButtons>

    <apex:pageBlockTable value="{!Accounts}" 
                         var="item" id="AccntTable">

                        <apex:column value="{!item.ID}"/>
                        <apex:column value="{!item.Name}"/>
                        <apex:column value="{!item.Phone}"/>

            </apex:pageBlockTable>

   
   </apex:pageBlock>
  
  </apex:form>
  
</apex:page>

 
Hello 

I am deserialize json input but face error as follows.

I am facing an error as:Unknown field: My_Invoice_list.InvoiceWrapper.invoiceList
Error is in expression '{!deserialize}' in component <apex:commandButton> in page vf_invoicelist: (System Code)
Class.My_Invoice_list.deserialize: line 39, column 1
An unexpected error has occurred. Your solution provider has been notified. (System)

Below is the apex class code and vf page code.
 
public class My_Invoice_list
{
   public class InvoiceList 
   {
        public Double totalPrice {get;set;} 
        public String statementDate {get;set;} 
        public List<LineItems> lineItems {get;set;} 
        public Integer invoiceNumber {get;set;} 
   }
   
   public class LineItems
   {
      public Double UnitPrice {get;set;} 
      public Double Quantity {get;set;} 
      public String ProductName {get;set;} 
   }
  
   public class InvoiceWrapper
   {
      public list<InvoiceList> invoice_wrapper{get;set;}
   }
   
   public InvoiceWrapper invoice{get;set;}
   
   public void deserialize()
   {
   
     Http p = new Http();
     
     HttpRequest request = new HttpRequest();
     
     request.setEndPoint('https://docsample.herokuapp.com/jsonSample');
     
     request.setHeader('Content-type', 'application/json');      
     
     request.setMethod('GET');
     
     HttpResponse response=p.send(request);
     invoice=(InvoiceWrapper)JSON.deserializeStrict(response.getBody(),InvoiceWrapper.class);
          
   }
}
 
<apex:page controller="My_Invoice_list">
<apex:form >

<apex:pageBlock title="Deserialize JSON Resposne">

<apex:pageBlockSection>
<apex:pageBlockSectionItem>

<apex:commandButton value="submit"
                    action="{!deserialize}"
                    reRender="invoicetable"/>
                    
</apex:pageBlockSectionItem>
</apex:pageBlockSection>
</apex:pageBlock>            

<apex:pageBlock>
<apex:pageBlockTable value="{!invoice.invoice_wrapper}"
                     var="inv"
                     id="invoicetable">

                      <apex:column value="{!inv.totalPrice}" headerValue="TotalPrice" />
                      <apex:column value="{!inv.statementDate}" headerValue="statementDate" />
                     
</apex:pageBlockTable>
</apex:pageBlock>   
</apex:form>
</apex:page>

I am not understanding how to display the line items. 

divya
 
Hi
I am trying to understand basics of displaying data in visual force page.
Below is the code:
public class HttpExample3
{
   public string result{get;set;}
   public Double grand_total{get;set;}
   public InvoiceList inv{get;set;}
   
   public string callservice()
   {
     Http p = new Http();
     
     HttpRequest request = new HttpRequest();
     
     request.setEndPoint('https://docsample.herokuapp.com/jsonSample');
     
     request.setHeader('Content-type', 'application/json');      
     
     request.setMethod('GET');
     
     HttpResponse response=p.send(request);
     
     return response.getBody();
               
    }
    
    public void GetTotalPrice()
    {
      grand_total=InvoiceList.TotalPrice(callservice());
    }
 }

<apex:page controller="HttpExample3">
<apex:form>
<apex:pageBlock title="GetResponse">

<apex:pageblockSection>

<apex:pageblockSectionItem>
<apex:commandButton value="GetResponse"
                      action="{!callservice}"/>


</apex:pageblockSectionItem>
</apex:pageblockSection>

</apex:pageBlock>

<apex:pageBlock title="TotalPrice"> 

<apex:pageblockSection>

<apex:pageblockSectionItem>
<apex:commandButton value="GetTotalPrice"
                      action="{!GetTotalPrice}"/>

 </apex:pageblockSectionItem>

</apex:pageblockSection>
 {!grand_total}
</apex:pageBlock>

</apex:form>

</apex:page>

public class InvoiceList
{
        public static Double totalPrice{get;set;} 
        public DateTime statementDate {get;set;} 
        public List<LineItems> lineItems {get;set;} 
        public Integer invoiceNumber {get;set;} 
        public static double grand_total=0.0; 
                       
        public static double TotalPrice(string jsonString)
        {
          System.JSONParser jp=JSON.createParser(jsonString);
          
          while (jp.nextToken() != Null)
          {
             if ((jp.getCurrentToken() == JSONToken.FIELD_NAME) && jp.getText() == 'totalPrice')
             {
               jp.nextToken();
               grand_total+=jp.getDoubleValue();     
             }
          }
          
         return grand_total;
       }

       public class LineItems
       {
        public Double UnitPrice {get;set;} 
        public Double Quantity {get;set;} 
        public String ProductName {get;set;} 
       }
 }

I am making callservice method have return type because I need the response in other calculations.
code works fine when I click Get Total price button , but it fails when I click callservice button.
I get error as : he name can only contain underscores and alphanumeric characters. It must begin with a letter and be unique, and must not include spaces, end with an underscore, or contain two consecutive underscores. "

Please help me .

divya

 
friends
I have a json file , I want to use deserializeuntyped method to understand it.

public class Jsonexample5
{
   public string result{get;set;}
   
   public Jsonexample5()
   {
     string jsonInput='{"response":{"count":1,"benchmark":0.22567009925842,"requests":[{"request":{"id":537481,"image_thumbnail":"","title":"Request for new bin(s) - residential","description":"Propmain ref  3234-1114","status":"submitted","address":"36 Pine Tree Close","location":"Peterborough, England","zipcode":"PE1 1EJ","user":"","date_created":1417173208,"count_comments":0,"count_followers":0,"count_supporters":0,"lat":52.599967,"lon":-0.233482,"user_follows":0,"user_comments":0,"user_request":1,"rank":"0"}}],"status":{"type":"success","message":"Success","code":200,"code_message":"Ok"}}}';
       
     Map<String,Object> jsmap = (Map<String,Object>)JSON.deserializeUntyped(jsonInput);
     system.debug('==>'+jsmap);
 
   }
}

I have 2 things to clarify
a) when I execute the above in developer console I get the deserialized format but it does not include attributes after location.
    i.e atrributes like zipcode , user , date_created , count_comments  etc are missing.

    The same input json string when executed in    http://codebeautify.org/jsonviewer#  gives all the attributes.

    I want to know why is this happening. Am I missing something:?


b) In real time scenario , do we use third pary tools to generate classes for json input or we have to manually write our own wrapper classes?

thanks
divya manohar
 
Hello
This is my first post.

I have a json string which I want to deserialize and get the values.

public class CompanyContactsWrapper
{
     public string contact{get;set;}
     public string postalcode{get;set;}
     public string contactnumber{get;set;}
}

public class Jsonexample4
{
   public CompanyContactsWrapper CompanyContacts{get;set;}
   
   public Jsonexample4()
   {
    
     string jsonInput='{"CompanyContacts":[{"contact":"pn0","postalcode":"0","contactnumber":"pc0"},{"contact":"pn1","postalcode":"1","contactnumber":"pc1"},{"contact":"pn2","postalcode":"2","contactnumber":"pc2"}]}';
          
          
     CompanyContacts= (CompanyContactsWrapper)JSON.deserialize(jsonInput,CompanyContactsWrapper.class);
         
     system.debug('==>'+CompanyContacts);
   
   }
}

In developer console I create an object and execute.
I get contact=null, postalcode=null & contactnumber=null.

pls tell where I have gone wrong?

thanks
divya manohar