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
Johannes SchausbergerJohannes Schausberger 

Include read-only field in SObject result

Hi,

I have a dynamically created Opportunity where i assign values according to some formula:
 

Opportunity opp = new Opportunity(Name='SomeName', Amount=2000, Probability=20);
Whatever the values might be.

Then i convert it to a JSON String:

return JSON.serialize(opp);



My problem here is: The JSON String only contains the Values used/assigned by me. That would be Name, Probability, Amount.

Result: 

{"Name":"SomeName", "Probability":"20", "Amount":"2000"}

But I need it to also contain ExpectedRevenue, which is calculated by Probability*Amount. It is a read-only field, so i cannot set it in the code.

Desired Result:

{"Name":"SomeName", "Probability":"20", "Amount":"2000", "ExpectedRevenue":"400"}
How can i accomplish this?
Best Answer chosen by Johannes Schausberger
Alexander TsitsuraAlexander Tsitsura
Hello Johannes,

As I understand, you need to generate a JSON and maybe the JSON Generator (https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_json_jsongenerator.htm) help you.

Please, see the example below, how to generate the JSON for your example:
JSONGenerator gen = JSON.createGenerator(true);
gen.writeStartObject();
gen.writeStringField('Name', 'SomeName');
gen.writeStringField('Amount', '2000');
gen.writeStringField('Probability', '20');
gen.writeStringField('ExpectedRevenue', '400');
gen.writeEndObject();

System.debug(gen.getAsString()); 
// {
//  "Name" : "SomeName",
//  "Amount" : "2000",
//  "Probability" : "20",
//  "ExpectedRevenue" : "400"
//}

If it helped you, then please select it the best answers it will help outer also.

Thanks,
Alex