Search code examples
symfonyfosrestbundlejmsserializerbundle

Convert json encoded String to json object in FosRestBundle


I have a json encoded string in one of my DB fields, e.g.

[{"name":"car","price":"10"}]

I'm using the FosRestBundle to return the DB-Values in json format and the String above is returned - as String - nothing special until here;)

How can this String be converted, so that a Json Object is returned instead?


Solution

  • Finally I found the solution.

    My Entity contained this:

    /**
     * @var string
     *
     * @ORM\Column(name="options", type="string", nullable=true)
     */
    private $options;
    

    "options" contained the json encoded string. So I tried it with the JMS Serilizer Annotation @Accessor and wrote this specific getter:

    /**
     * Get optionsAsArray
     *
     * @return array
     */
    public function getOptionsAsArray()
    {
        return (array)json_decode($this->options, true);
    }
    

    Still got an error "Array to string conversion". So the Solution was, to add another Annotation @type and the JMSSerializer returned nicely formatted JSON.

    This is what the Entity has to look like:

    use JMS\Serializer\Annotation\Accessor;
    use JMS\Serializer\Annotation\Type;
    
    
    /* ... */
    
    /**
     * @var string
     *
     * @ORM\Column(name="options", type="string", nullable=true)
     * @Accessor(getter="getOptionsAsArray")
     * @Type("array")
     */
    private $options;