4

I am using JMS\Serializer in my project and I want to ignore one property only if the array in it is empty.

I tried something like :

@JMS\Exclude(if="count('$this->required') === 0")
or 
@JMS\Exclude(if="empty('required')")

but got a syntax error.

Can anyone help me on this?

thank.

cosmoonot
  • 2,161
  • 3
  • 32
  • 38
  • as far as i can read the docs you can use `@JMS\Exclude(if="<1")` , could you try ? – john Smith May 01 '17 at 21:19
  • if not try the "exclusionStrategy" http://stackoverflow.com/questions/21916450/how-do-i-create-a-custom-exclusion-strategy-for-jms-serializer-that-allows-me-to – john Smith May 01 '17 at 21:21
  • What you need was implemented recently and it is in release-1.7 so you might as well wait for [it](https://github.com/schmittjoh/serializer/releases). It is called [@SkipWhenEmpty](https://github.com/schmittjoh/serializer/pull/757/files#diff-9828fde36b4c4800e1d437a28538de94R35) This is the [bug](https://github.com/schmittjoh/JMSSerializerBundle/issues/373) related it. "`@SkipWhenEmpty` This annotation can be defined on a property to indicate that the property should not be serialized if the result will be 'empty'". – BentCoder May 02 '17 at 15:26
  • oh thank @BentCoder. it's exactly what I need. i hop it will be merged soon. – Mathieu Delisle May 02 '17 at 15:59
  • @MathieuDelisle I added it as an answer below so if you could kindly accept it, everybody else would have an idea of the possible solution. – BentCoder May 02 '17 at 16:05

2 Answers2

7

What you need was implemented recently and it is in release-1.7 so you might as well wait for it. It is called @SkipWhenEmpty

@SkipWhenEmpty This annotation can be defined on a property to indicate that the property should not be serialized if the result will be "empty".

This is the bug related it.

BentCoder
  • 12,257
  • 22
  • 93
  • 165
2

You need this one:

@JMS\Exclude(if="!object.required")
Zombie
  • 21
  • 1