+ Start a Discussion
Johannes SchausbergerJohannes Schausberger 

Include read-only field in SObject result


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.


{"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.writeStringField('Name', 'SomeName');
gen.writeStringField('Amount', '2000');
gen.writeStringField('Probability', '20');
gen.writeStringField('ExpectedRevenue', '400');

// {
//  "Name" : "SomeName",
//  "Amount" : "2000",
//  "Probability" : "20",
//  "ExpectedRevenue" : "400"

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