I have an object which is converted to string in a text field. How can I convert this to a JSON string.

String of object:

Profile:[UID=, crmId=0000o00002XXXXxXXX, [email protected], firstname=null, lastname=test]

I tried JSON.serialize(textfield); but this only sets "" arount the text

I want to convert this to the following:

{ "email" : "[email protected]",
"crmId" : "0000o00002XXXXxXXX",
"firstname" : "null",
"lastname" : "test",
"UID" : ""
  • any chance the supplier of this info can preserve the original Json so you don't need to go through this conversion?
    – cropredy
    Jan 21, 2020 at 19:10
  • @cropredy This could only be possible in this case if the object cloud be saved in a salesforce field but as far I know this ist possible, any suggestions?
    – Thomas
    Jan 21, 2020 at 19:12
  • Is the ID of the real object in this text string representation of the object? Are you able to just query it and then serialize the actual object record? Jan 21, 2020 at 19:40

1 Answer 1


You can easily parse your String into Map and then serialize Map itself.

Here is an example how to do it:

String toMap = 'Profile:[UID=, crmId=0000o00002XXXXxXXX, [email protected], firstname=null, lastname=test]';

Map<String, String> ans = new Map<String, String>();
String actualValues = toMap.substringAfter(':');
actualValues = actualValues.substring(1, actualValues.length()-1);

for (String val : actualValues.split(', ')) {
    ans.put(val.substringBefore('='), val.substringAfter('='));

String jsonString = JSON.serialize(ans);

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .