3

I have this very simple example that serializes and deserializes the first Account found:

System.debug((Account) JSON.deserialize(
    JSON.serialize([SELECT Id, Name FROM Account LIMIT 1]),
    Account.class)
);

It fails with an error:

System.JSONException: Json Deserialization failed on token 'null' and has left off in the middle of parsing a row. Will go to end of row to begin parsing the next row

With no own code whatsoever - why does this fail? And what can I do to get it running?

EDIT:

I was actually super confused as to why this happens and even more confused about the fact that this confused me. The solution is actually pretty simple. The following lines both work:

Account account = [SELECT Id, Name FROM Account LIMIT 1];
List<Account> accounts = [SELECT Id, Name FROM Account LIMIT 1];

Since the list is directly passed into the serializer it cannot know if you want a list or a single object - therefore throwing the error.

0

2 Answers 2

5

It's because the query returns a List<Account> unless you specify it somewhere as a single Account record.

Works

Account data = [SELECT Id, Name FROM Account LIMIT 1];
system.debug(JSON.deserialize(JSON.serialize(data), Account.class));

Fails

List<Account> data = [SELECT Id, Name FROM Account LIMIT 1];
system.debug(JSON.deserialize(JSON.serialize(data), Account.class));

The second example above exactly matches the behavior you observed. You could also still one-line it:

system.debug((Account)JSON.deserialize(
    JSON.serialize((Account)[SELECT Name FROM Account LIMIT 1]), // you must cast here
    Account.class
));
0
3

The JSON.deserialize is returning a List<Object> not Object. Below Debug is working fine:

System.debug((List<Account>)JSON.deserialize(String.valueOf(JSON.serialize([SELECT Id, Name FROM Account LIMIT 1])), List<Account>.class));
2
  • Thanks! Your answer actually helped me to understand why I hit this problem in the first place. Basically you can just always select a list somewhere - if it contains exactly one item you can directly assign it to an SObject. For some reason this magic doesn't work here as you have to be explicit in what you're doing. I will update my question accordingly to account for this finding.
    – Semmel
    Jul 4, 2019 at 17:00
  • Of course the magic doesn't work here - there's no intermediate object or list therefore the serializer cannot know what to do.
    – Semmel
    Jul 4, 2019 at 17:15

You must log in to answer this question.

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