+ Start a Discussion
brian49brian49 

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!

TanejaTaneja

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

venusvenus

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++;
}

}
}

Markus Koch 7Markus Koch 7
Hey I stumbled upon this thread and didn't find a good solution. But here is how I solved it now: I have a class called JSON2 that has the same methods as the JSONGenerator but including the logic of handling null/empty values:
 
public class JSON2  {
	
	public static void writeStringField(JSONGenerator gen, String fieldName, String fieldValue) {
		if(String.isEmpty(fieldValue)) {
			gen.writeNullField(fieldName); // Could be replaced with writeStringField(...,'') if you prefer an empty string over a null field
		} else {
			gen.writeStringField(fieldName, fieldValue);
		}
	}
}
In the place where I generate the JSON it now looks like this:
JSONGenerator gen = JSON.createGenerator(true);
gen.writeStartObject();
JSON2.writeStringField(gen, 'name', 'Test');
gen.writeEndObject();
Works like a charm ;)