I am having some issues when I generate a JSON to be send via web service, the field is a currency formula field but some long numbers are showing in scientific notation, when the web service read the value throws an error, this is the code I am using to create the JSON:

JSONGenerator gen = JSON.createGenerator(true);
for(Account acc : accounts){            
        gen.writeStringField('ID', acc.Id);

and this is the JSON I get:

{ "ID" : "0013600000vy0KFAAY", "TotalDonadoHistorico" : 1.68E+7 }

The number in the field is 16800000.00.

Some one have a workaround how to deal with this issue?

  • I used setscale() decimal class method to get the complete number – Angello Camacho Apr 14 '18 at 20:32

This code:

Map<String, Decimal> m = new Map<String, Decimal>{
    'TotalDonadoHistorico' => 16800000.00



i.e. does generate the desired format. And in general using JSON.serialize is much easier than using the JSONGenerator so I suggest you re-implement using JSON.serialize.

For your case the code would look something like this:

// This is equivalent to a list of objects in JSON i.e. [{...}, {...}]
List<Map<String, Object>> l = new List<Map<String, Object>>();
for(Account acc : accounts) {
    // This is equivalant to an object in JSON i.e. {...}
    Map<String, Object> m = new Map<String, Object>();
    m.put('Id', acc.Id);
    if (acc.Total_Donado_Hist_rico__c!=null){
        m.put('TotalDonadoHistorico', acc.Total_Donado_Hist_rico__c); 
String jsonString = JSON.serialize(l);
| 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.