Find your content:

Search form

You are here

Why does JSON serialization give different results when the Sobject is created from a SOQL query and when the Sobject is instantiated normally?


I am getting some very odd behavior from the JSON serializer where if the Sobject was originally instantiated from a SOQL query it will exclude any fields that were not part of my query from the serialized JSON string even if I fill in those fields later in my code.

sample code:

Contact con = [select id, lastname, accountid from Contact limit 1];
string jsonstring = Json.serialize(con);
System.Assert(jsonstring.contains('foo') == false); //this should not be happening

Contact newcon = new Contact(id=con.ID,lastname=con.Lastname,accountid=con.AccountID);
jsonstring = Json.serialize(newcon);

UPDATE: This was fixed in Spring '13!

Attribution to: Greg Grinberg

Possible Suggestion/Solution #1

From speaking with salesforce support this is a known issue with no current time frame for when this will be fixed.

As Peter said the only workaround is to include all the fields in the query that you want to show up in the JSON.

UPDATE: This was fixed in Spring '13!

Attribution to: Greg Grinberg

Possible Suggestion/Solution #2

I do not see anything in the System JSON methods or JSON Parser methods that document the behavior that you observe. I don't see anything in the Getting Started with Apex wiki article. I don't see anything in the SOQL and SOSL guide. I also found nothing in the Salesforce Known Issues

The serialize method documentation is:

Serializes Apex objects into JSON content. The object argument is the Apex object to serialize.

The following example serializes a new Datetime value.

 Datetime dt =
                   2011, 3, 22),
                   1, 15, 18, 0)); 
     String str = JSON.serialize(dt); 

I executed your exact code from Execute Anonymous from my IDE and observed the exact same behavior.

My conclusion is that I either am not finding the correct documentation, this is the correct behavior and the documentation is lacking, or this is a SF issue.

I also modified your SOQL to:

Contact con = [select id, lastname, firstName, accountid from Contact limit 1];

Then set the first name the same:

con.firstName = 'foo';

This does result in 'foo' being in the jsonstring.

Obviously, the workaround is to always select all of the fields that you need to appear in the jsonstring or construct the new instance like you did.

Attribution to: Peter Knolle
This content is remixed from stackoverflow or stackexchange. Please visit

My Block Status

My Block Content