5

I am creating a symfony2 project and using the JMS serializer bundle to serialize my object for database storage (I know this is not the best way).

But now my problem is, when I change a property of my object and deserialize the Json string the JMS serializer ignores non existing properties instead of throwing an error, which is actually great. Yet I would like to log such an event.

Below is an example to illustrate my question

Json string from my database:

$dataToBeDeserialized = {"title":"testing123","text":"Lorem Ipsum"}

TestClass:

/**
 * @Type("string") 
 */
protected title;

/**
 * @Type("string") 
 */
protected text;

Deserialize method:

$this->serializer = SerializerBuilder::create()->build();
$this->serializer->deserialize($dataToBeDeserialized, 'TestClass', 'json');

This results in:

TestClass {
  title: "testing123",
  text: "Lorem Ipsum"}

But when I change my Testclass and rename (or remove) title to, let's say, "title2", The deserializer ignores the "title" attribute in the Json string. and that results in:

  TestClass {
  title2: "",
  text: "Lorem Ipsum"}

Well no problem there. The data in the database is wrong. But I would like to log that problem. How should I do this? I don't want to mess in the code of the JMS serializer if possible (since I cannot update it anymore). And looking for empty properties in my TestClass isn't the best way either, since they can be null.

Dushyant Joshi
  • 3,672
  • 3
  • 28
  • 52
Mr.wiseguy
  • 4,092
  • 10
  • 35
  • 67

1 Answers1

0

The JMS Serializer allows to be configured with handlers and event listeners, in your case I think a event listener would suffice as you will just be waiting for the occurence of a certain situation (an unmatched attribute). At that point you simply want to write it to log, so the course would be the following:

  1. Create a listener class which implements JMS\Serializer\EventDispatcher\EventSubscriberInterface
  2. Make the listener write a log line when your condition is met.
  3. Subscribe this listener to an event.

I will write a more detailed description when I get home from work this evening but I thought maybe this can help you along already.

Check out the docs for more details: http://jmsyst.com/bundles/JMSSerializerBundle/master/configuration#event-dispatcher And the default subscribers might give you a clue: https://github.com/schmittjoh/serializer/tree/master/src/JMS/Serializer/EventDispatcher/Subscriber