+ Start a Discussion
jadentjadent 

Object to string and back

I recently learned that classes in apex inherit a toString method which outputs the instantiated object to a string (much like serialization does in some languages). I cannot seem to find any documentation on this inherited method can someone point me in the right direction? 

 

Also once its in a string how can then convert that string to an object again?

 

Thanks 

Message Edited by jadent on 09-02-2009 11:52 AM
AmphroAmphro

It just like Java. In Java, Object has a toString method. Since every object extends Object, they also have a toString method. One cool thing is in Apex, everything is an object including primitives.

However, Apex doesn't have a toString method. Every object can be converted to a string by using String.valueOf(someObject). This is what gets called, someone correct me if I am wrong, when you concatenate string with object. So for example.

String myString = intVar + booleanVar + sObjectVar + 'some string';

All that is doing is calling String.valueOf on each one of those variables. 

Also, this method gives much more information than the toString in Java.

However, once a sting, it can not be converter back to an object. You would have to write your own method to do that.

 

 

 

jadentjadent

All classes i create in apex inherit a toString method. If i create an class say CustomClass, i can do this

 

CustomClass c = new CustomClass();

c.toString();

 

and it will output it just like String.valueOf(c). Its inherited. But i don't see any documentation on it. Since its inherited i figured there would be a way to convert it back as well.

AmphroAmphro

Ohh alright cool, for some reason it gives me an error when I try that.

And I could be proven wrong again, but I do highly doubt you can convert back to the object from the srting. 

IanRIanR

If you need to convert your string back into an object, you can just assign it directly - no conversion method is required,

 

e.g.

 

string myString = 'This is a string'; object myObj = myString;

 

 

 

AmphroAmphro

Do you know what that will do? Does it assign the object name to the string?

David VPDavid VP

As in Java, the toString() method is not meant to be used for serialization/deserialization purposes. It merely serves as an easy shortcut to output object information in an application or debugging output.

 

If you want to serialize object info, you could for example create an XML representation of that and send that over the wire or persist it somewhere.

jadentjadent

I can assign it to an Object but how would i cast it back into the original object?Example, i have a class CollectionWrapper which i would like to store in a string and bring back later.Trying to cast it back will give a System.TypeException: Invalid conversion from runtime type String to CollectionWrapper

 

String myString = 'CollectionWrapper:[m={Name=Smith}] '; Object myObj = myString; CollectionWrapper myCW = (CollectionWrapper) myObj;

 Any thoughts on how to get it back into the original object?


 

AmphroAmphro

You could do it a few ways. Either way, I think you have to parse the string and rebuild the object. I would override the toString method and construct the string in a way so the constructor can build the object again. So then it would look something like this.

String myString = myCatagoryWrapper.toString();
CategoryWrapper cw = new CategoryWrapper(myString);
You could also have a static method that takes a string and returns a CategoryWrapper.
Rahul SharmaRahul Sharma

Dear board,

 

Today i ran into same issue when i tried to built an application with use of dynamic dml .

After struggling a lot i found that sObject.get('FieldName') returns a Object instead of a Stiring.

Due to which i hit with error as : 

Error:

Value 'Mon Jan 16 00:00:00 GMT 2012' cannot be converted from Text to Date

Then later on i found a solution with use of typecasting as .toString() method does not works here.

Posting this for others who might face similar issue.

Just we need to type cast the values:

string myString = 'This is a string'; 
object myObj = myString;
system.debug('==Object=='+myObj );
myString = (String) myObj;
system.debug('==String=='+myString);

 

 

twangitwangi

Warning to anyone reading these posts, apparently not every object has a toString method:

 

Error: Compile Error: Method does not exist or incorrect signature: [Object].toString() at line 329 column 45

 

 

I'm trying to use the result of a JSON.deserializeUntyped into a Map<String,Object> structure then make use of the Object part of it as per http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_methods_system_json.htm.

ApuroopApuroop
@twangi
I agree with you. But in your case, you might wanna add the objects to a new List<Object>  and then try using the .toString() method on the brand new list.

Here's a snippet from the trailheads, LINK (https://trailhead.salesforce.com/content/learn/modules/apex_integration_services/apex_integration_rest_callouts)
Http http = new Http();
HttpRequest request = new HttpRequest();
request.setEndpoint('https://th-apex-http-callout.herokuapp.com/animals');
request.setMethod('GET');
HttpResponse response = http.send(request);
// If the request is successful, parse the JSON response.
if (response.getStatusCode() == 200) {
    // Deserialize the JSON string into collections of primitive data types.
    Map<String, Object> results = (Map<String, Object>) JSON.deserializeUntyped(response.getBody());
    // Cast the values in the 'animals' key as a list
    List<Object> animals = (List<Object>) results.get('animals');
    System.debug('Received the following animals:');
    for (Object animal: animals) {
        System.debug(animal);
    }
}
Now we can do something like this,
String foo = animals[1].toString();
System.debug(foo);

Thank you!!
ApuroopApuroop
I wanna add to my previous answer,
This converts an object to string. Notes: LINK
Object object1 = new Object();
String foo = String.valueOf(object1);
System.debug(foo);