function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
sandipmsandipm 

Dynamic SOQL: extracting value from sObject field

Hi,

  I think this should be quite straightforward question as everyone seem to know abt it. I didnt find any question similar to this on discussion board. 

 

What I am trying to do is...this is just simplified version...

 

List<sObject> L = Database.query('select name, id from Account where id in : recordIds');

for (sObject c : L){

        customObject__c customObject = new customObject__c(); 

customObject.name = c.get('name'); 

 

 type of name is string. while c.get is returning something of type 'object'. how to convert object to string?

simple casting is not working. it fails at compile time only.

 

 it will save me lots of extra lines of code, if I get solution for this.

 

 I am not able to find in any document, of how to convert this object into string. 

 

  

 TIA.

 

regards,

Sandip 

 

Best Answer chosen by Admin (Salesforce Developers) 
sandipmsandipm

This was quite simple finally but took time to got it..as solution was other way round.

Object is anytype data type. to convert it to string, straight forward casting (string) object  doesnt work.

You have to do String.valueOf(object) to get the string value of object. similar method exists for other standard data types like datetime, Integer, double.

 

 

regards

Sandip 

 

 

All Answers

sandipmsandipm

This was quite simple finally but took time to got it..as solution was other way round.

Object is anytype data type. to convert it to string, straight forward casting (string) object  doesnt work.

You have to do String.valueOf(object) to get the string value of object. similar method exists for other standard data types like datetime, Integer, double.

 

 

regards

Sandip 

 

 

This was selected as the best answer
fgwarbfgwarb

 

for(sObject attach : attachments){
 Object o = attach.get('Body');
 Blob b = Blob.valueOf(o);
 String strReport = String.valueOf(b);
 //do work
}

 

I'm trying to get the body of an attachment into a String; there is no method Blob.valueOf(object).  Only Blob.valueOf(String).

 

If I cast the object to a string it turns into this literal value "Blob[xxx]"  where xxx = the size of the blob. 

 

Anyone have any advice?  I've worked around it by burning a SOQL query, but this shouldn't be necessary.

 

 

Blob b = [SELECT Body FROM Attachment WHERE Id = :String.valueOf(attach.get('id')) LIMIT 1].Body;
String strReport = b.toString();

 

 

 

SuperfellSuperfell

Blob b = (Blob)attach.get("Body");

fgwarbfgwarb

Glorious!  

 

I don't understand the syntax though, can you point me to somewhere (online) that explains it?  

 

I saw some references to it in the SF Apex documentation but I (obviously) didn't understand how to use it.