Tell me more ×
Salesforce Stack Exchange is a question and answer site for Salesforce administrators, implementation experts, developers and anybody in-between. It's 100% free, no registration required.

Let's say I have a virtual class and two classes that extend it and I am getting a JSON response that could be either one of those classes. Is there a way to deserialize the JSON into the appropriate class without examining it manually?

Here are my classes:

public with sharing virtual class BaseClass
{
public Integer id;
}

public with sharing class foo extends BaseClass
{
public String foo;
}

public with sharing class bar extends BaseClass
{
public Integer bar;
}

I want to be able to do something like

Json.deserialize(jsonstring,Class.BaseClass.Descendants)
share|improve this question

2 Answers

up vote 2 down vote accepted

If your JSON always has an id, but also has either a foo or a bar, I think the corresponding Apex would be

public class Thing {
    public Integer id;
    public String foo;
    public Integer bar;
}

You would deserialize into a Thing, then test whether foo or bar was null. There's no way to persuade the parser to pick the correct subclass.

share|improve this answer
Well, my actual scenario is that my base class has a few fields and the classes extending it each have many fields. I am trying to integrate with an API that returns a whole bunch of JSON objects and I was hoping that I could do the JSON deserialization as part of my generic response handler (since all the error handling and such is the same no matter what object I'm getting) – Greg Grinberg Sep 12 '12 at 13:12
Is there anything in your data that tells you what kind of object you need to create, before you hit the object itself? – metadaddy Sep 12 '12 at 20:25
Yes, the endpoint for each object is different. I.E. /user, /account etc. I can definitely figure out which object to deserialize to. Was just hoping there was some generic way to do this. – Greg Grinberg Sep 12 '12 at 21:56

I don't think it is possible.

JSON is a data only object, and has no knowledge of your classes.

You would need to embed the name of your class and check that when de-serializing.

share|improve this answer
Is this possible in Apex? That is, is there an analogue to Java's instance.getClass().getName()? – Benj Sep 12 '12 at 14:20
2  
Answering my own question! There is instance.class.getName() [salesforce.com/us/developer/docs/apexcode/Content/… ] – Benj Sep 12 '12 at 15:49
1  
@Benj sadly .class.getName() doesn't work on the instance, it works on the class as if "class" were a static property. I'm not aware of any way to get a System.Type object from an actual instance of a class, only from the class itself. – ca_peterson Sep 13 '12 at 0:27

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.