2

I'm trying to use the System method JSON.deserialize(jsonString, apexType) to deserialize the body of an ApexRest POST request. My code compiles, but at runtime I'm getting a System.NullPointerException from the line making the JSON.deserialize() call.

Here's a snippet of my code.

RestRequest req         = RestContext.request;
String      jsonString  = req.requestBody.toString();
System.Type myType      = System.Type.forName('PostDataWrapper');

// This next line throws a System.NullPointerException
PostDataWrapper postData = (PostDataWrapper)JSON.deserialize(jsonString, myType);

I've confirmed that the requestBody body has the correct JSON payload, and I'm sure that I have a PostDataWrapper type because it's declared in the ApexRest class itself as an inner class.

Where is the System.NullPointerException coming from?

3

The problem is with the value passed to the System.Type.forName() call.

This method requires a "fully qualified" class name. Since the PostDataWrapper class was declared as an inner class, you need to prepend the name of the outer class to the string parameter.

If the outer class was named MyRestClass, then your call would look like this:

System.Type myType = (PostDataWrapper)System.Type.forName('MyRestClass.PostDataWrapper');

Calling the System.Type.forName() method with the correct, "fully qualified" type name should place a non-null value into the myType variable. This should allow the call to JSON.deserialize() to succeed (assuming there aren't any serialization errors).

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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