Symfony2 Discovery Log - JMSSerializer - Don't forget @SerializedName!

It's a bit late, so I apologize in case my grammar and spelling may be a bit off.

JMSSerializer is a library for Symfony that allows users to serialize and de-serialize data of any complexity.  I was using the library to try to deserialize my JSON that is being passed to the data models for this project that I'm currently working on, but was recently stuck on figuring out why when I deserialize the JSON, the values ended up being null.  I was sure that I had everything set up just fine:

  • JSON was being passed in via AJAX.
  • JSON was able to be retrieved in the controller.
  • Responses were being sent back to the view.

After spending hours checking, double-checking, and triple-checking my code, I realized there was a JMSSerializer annotation that I wasn't using for my entity class, @SerializedName.  From the documentation:

"This annotation can be defined on a property to define the serialized name for a property. If this is not defined, the property will be translated from camel-case to a lower-cased underscored name, e.g. camelCase -> camel_case."  

Since I did have a few properties that were camel-case in my JSON, using the @SerializedName annotation allowed the JSON to be deserialized properly into the designated entity.  

  1. /**
  2.  * @Type("string")
  3.  * @SerializedName("someString")
  4.  */
  5. private $someString;

If the property name was written in camel-case and the @SerializedName annotation wasn't used in the entity class, then the serializer has no way of knowing what property to assign the value to which means it ends up being NULL.  The string value for the @SerializedName annotation should be the same as the property name coming in with your JSON so that they are matching.  For more information regarding the use of the JMSSerializer annotation reference, please go to  http://jmsyst.com/libs/serializer/master/reference/annotations.