You need to sign in to do that
Don't have an account?
Using potentially null string values with JSON generator
I'm trying to write out JSON from multiple Salesforce objects using the JSONGenerator class, with the below lines as a small example.
JSONGenerator gen = JSON.createGenerator(true);
gen.writeStartObject();
gen.writeStringField('companyname', account.name);
gen.writeStringField('permalink', opp.permalink__c);
gen.writeEndObject()
When writing the string fields, I can't guarantee the string won't be null (for example, that opp.permalink__c is null), which means that the generator throws an error when I try when I attempt to write a null string. To get around it, I could do a null check on every field, and set it to the empty string instead of null, but I'm retrieving a lot of fields and don't want to make the code too unreadable... Is there a cleaner fix for this?
Thanks in advance!
Hey Brian,
I am going through the same problem. Did you find a solution to it yet? If yes, please share, it would be a great help.
Best,
Taneja
Hi friends i also face this porblem i come up with solution try it once
WebService static void createJsonRequest(JSONGenerator tempgen,String FieldName,List<String> values)
{
if(FieldName != '')
{
tempgen.writeFieldName(FieldName);
tempgen.WriteStartObject();
for(Integer i=0;i<values.size()-1;i++)
{
String Fieldval='';
if(values[i+1] == null)
{
Fieldval ='';
}
else
{
Fieldval= values[i+1];
}
tempgen.WriteStringField(values[i],Fieldval);
i++;
}
tempgen.WriteEndObject();
}
else
{
for(Integer i=0;i<values.size()-1;i++)
{
String Fieldval='';
if(values[i+1] == null)
{
Fieldval ='';
}
else
{
Fieldval= values[i+1];
}
tempgen.WriteStringField(values[i],Fieldval);
i++;
}
}
}
In the place where I generate the JSON it now looks like this: Works like a charm ;)