0

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);
gen.writeStartArray();
for(Account acc : accounts){            
    gen.writeStartObject();
        gen.writeStringField('ID', acc.Id);
    if(acc.Total_Donado_Hist_rico__c!=null){
            gen.writeNumberField('TotalDonadoHistorico',acc.Total_Donado_Hist_rico__c); 
    }
    gen.writeEndObject();
}
gen.writeEndArray();

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?

1
  • I used setscale() decimal class method to get the complete number Commented Apr 14, 2018 at 20:32

1 Answer 1

0

This code:

Map<String, Decimal> m = new Map<String, Decimal>{
    'TotalDonadoHistorico' => 16800000.00
};
System.debug(JSON.serialize(m));

outputs:

{"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); 
    }
    l.add(m);
}
String jsonString = JSON.serialize(l);

You must log in to answer this question.

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