1

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=top@top.com, 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" : "top@top.com",
"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 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 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? – Kris Goncalves Jan 21 at 19:40
3

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=top@top.com, 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);
system.debug(jsonString);
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.