JMS Serialize @VirtualProperty doesn't work

13,684

I've noticed the problem. There was created before the object "$ ad". My fault. Virtual property functioning properly.

Share:
13,684
escrichov
Author by

escrichov

Updated on August 02, 2022

Comments

  • escrichov
    escrichov almost 2 years

    I'm trying to add a method to serialize, but JMS Serialize does not show the field.

    use JMS\Serializer\Annotation\Groups;
    use JMS\Serializer\Annotation\VirtualProperty;
    use JMS\Serializer\Annotation\SerializedName;
    
    class Ads
    {   
        /**
         * @VirtualProperty
         * @Type("string")
         * @SerializedName("Foo")
         * @Groups({"manage"})
         */
        public function foo(){
            $foo = 'foo';
            return $foo;
        }
        ...
    }
    

    And then:

    use JMS\Serializer\SerializationContext;
    use JMS\Serializer\SerializerBuilder;
    
    ...
    
    $context = new SerializationContext();
    $context->setGroups(array('manage'));
    
    $serializer = JMS\Serializer\SerializerBuilder::create()->build();
    $jsonContent = $serializer->serialize($ad, 'json', $context);
    

    I have not seen any examples of how to use VirtualProperty.

    Is the syntax correct? What is wrong?

    Thank you.

  • Soullivaneuh
    Soullivaneuh about 9 years
    What was the problem? How did you fix it? Try the same with a yaml config, not work either... Thanks.
  • Soullivaneuh
    Soullivaneuh about 9 years
    Ok found why. Yaml configuration is quite different. You have to separate virtual properties. See here: jmsyst.com/libs/serializer/master/reference/yml_reference
  • martin
    martin about 7 years
    This is supposed to explain where was the problem but I don't understand that sentence ... :(
  • Dessauges Antoine
    Dessauges Antoine over 5 years
    If somebody (like me) doesn't understand the answer, this will maybe help you. In my case, the problem was that I have not add use JMS\Serializer\Annotation\VirtualProperty; and use JMS\Serializer\Annotation\SerializedName; at the top of my file